What will be passed if I DI HttpClient directly when using IHttpClientFactory in ASP.NET Core

less than 1 minute read

If you look at Documents of IHttpClientFactory, you can receive IHttpClientFactory and do CreateClient or specify the type. There is a method to receive HttpClient using the provided client function, but what if I have HttpClient DI in a normal untyped class? It seems that it is not explicitly written, so I checked it. (I’m sorry if it was written)

The answer was in the code below.


When AddHttpClient is done to IServiceCollection, HttpClient is also registered internally and it seems that the instance of the result of CreatingClient (string.Empty) of IHttpClientFactory is passed.


// Register default client as HttpClient
services.TryAddTransient(s =>
    return s.GetRequiredService<IHttpClientFactory>().CreateClient(string.Empty);

So if you just receive IHttpClientFactory and createClient, you may want to receive HttpClient directly.

Huh, refreshing.