Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 925
Test45 Avatar asked Jul 24 '18 12:07

Test45


People also ask

What is the use of HttpClientFactory?

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.

What are the differences between HttpClientFactory and HttpClient?

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.

Is HttpClientFactory thread safe?

HttpClient is a mutable object but as long as you are not mutating it, it is actually thread safe and can be shared.

Is AddHttpClient a singleton?

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 .


1 Answers

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.

like image 144
Panagiotis Kanavos Avatar answered Oct 05 '22 23:10

Panagiotis Kanavos