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.
Not only that HttpClientFactory can create and manage new HttpClient instances but also, it works with underlying handlers. Basically, when creating new HttpClient instances, it doesn't recreate a new message handler but it takes one from a pool. Then, it uses that message handler to send the requests to the API.
It has a method CreateClient which returns the HttpClient Object. But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood.
HttpClient is a mutable object but as long as you are not mutating it, it is actually thread safe and can be shared.
Http NuGet package that includes the AddHttpClient extension method for IServiceCollection. This extension method registers the internal DefaultHttpClientFactory class to be used as a singleton for the interface IHttpClientFactory .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With