Test45
Test45

Reputation: 593

Use HttpClientFactory from .NET 4.6.2

I have a .NET 4.6.2 console application (using Simple Injector). I need to make calls to an HTTP service. Having run into issues using HttpClient directly, I'm trying to use HttpClientFactory ( https://github.com/aspnet/HttpClientFactory ) instead.

The project/library is .NET Standard 2.0 so it should?? work in .NET 4.6.2, but it uses stuff like IServiceCollection, which is in Core only.

So my question is can I use HttpClientFactory in a non-Core application.

Upvotes: 50

Views: 54170

Answers (2)

Jim
Jim

Reputation: 509

As @Panagiotis Kanavos said, you need to add
Microsoft.Extensions.Http and Microsoft.Extensions.DependencyInjection.
Here is my ConsoleApp code, you can refer to it.

class Program
{
     static void Main(string[] args)
     {
         Test();
         Console.Read();
     }

     static async void Test()
     {
        var services = new ServiceCollection();
        //services.AddSingleton<xx,xx>();
        //...
        services.AddHttpClient();
        var serviceProvider = services.BuildServiceProvider();
        
        var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
        var client = httpClientFactory.CreateClient();
        var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://www.baidu.com"));
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(content);
     }
}

Upvotes: 37

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131704

All of the Microsoft.Extensions.* packages target .NET Standard 2.0. That means that you can use Dependency Injection, Configuration, Logging and HttpClientFactory if you add the appropriate package to your application.

You need to add Microsoft.Extensions.Http to use HttpClientFactory and Microsoft.Extensions.Http.Polly if you want to use it with Polly

To configure HttpClientFactory you'll have to add Microsoft.Extensions.DependencyInjection to your "main" project. Microsoft.Extensions.Http package only depends on Microsoft.Extensions.DependencyInjection.Abstractions which contains the interfaces, not the DI provider itself.

Upvotes: 59

Related Questions