Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core services.AddHttpClient - IHttpClientFactory vs HttpClient injection

I'm trying to understand something I've seen in some production code and when investigating it I found this page: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

The code I've seen is an ASP.NET Core Web App. It uses the AddHttpClient() extension:

services.AddHttpClient();

According to the documentation this injects an IHttpClientFactory into the controllers. But the production code declares the constructors like so:

public SomeController(ILogger<SomeController> logger, HttpClient client) {...}

I did some testing and this works too (with necessary adjustments of course):

public SomeController(ILogger<SomeController> logger, IHttpClientFactory factory) {...}

According to the documentation an HttpClient is injected into typed clients. But doesn't that require me to specify the type by using

services.AddHttpClient<T>();

?

I don't do that so is the type infered some way?

The IServiceCollection must do some magic based on what I choose to declare in the constructor. I cannot find any examples that use the combination of

services.AddHttpClient();

and

public SomeController(HttpClient client){...}

Can I find that documented somewhere?

like image 598
peterpop Avatar asked May 25 '26 10:05

peterpop


1 Answers

IHttpClientFactory has several consumption patterns of which typed clients is one among: named, generated or basic client.

What you are asking for (not registering a typed client, but resolving httpclient from DI) is possible but not recommended, so the usage patterns here don't show that. Also its not a "TypedClient" but a client reserved by type- this client itself doesnt change, just its 'stickiness' to the type that is using it. The redesign around the client factory is built around improper usage of clientfactory, from the doc you quoted:

However, the issue isn't really with HttpClient per se, but with the default constructor for HttpClient, because it creates a new concrete instance of HttpMessageHandler, which is the one that has sockets exhaustion and DNS changes issues mentioned above.

this stack overflow question might help clarify further.

Regarding how DI actually works, Here is the code doing the registration, see how it adds a HttpClient and bits of code which would be called on resolution - How it reserves a client by type, name etc.

like image 127
Hananiel Avatar answered May 30 '26 04:05

Hananiel