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.

https://github.com/dotnet/runtime/blob/254ef0f7f7f429ec238735fe6132805e3c38a19f/src/libraries/Microsoft.Extensions.Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs#L59

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.

HttpClientFactoryServiceCollectionExtensions.cs


// 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.