Precautions when using IHttpClientFactory in ASP.NET Core

1 minute read

IHttpClientFactory makes it easy to use HttpClient, which has a habit of using it.

Make HTTP requests in ASP.NET Core using IHttpClientFactory (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1)

CreatingClient from IHttpClientFactory is convenient because it can be used in a good way, discarded at the right time, and so on. With a named client, it feels even better because IHttpClientFactory is passed an HttpClient that is configured as configured without relying on it.

The important thing about using IHttpClientFactory is to create an instance of HttpClient when you need it and let it go when you no longer need it (you don’t have to dispose it).

Singleton? 

So if you DI an HttpClient or a typed client to the Singleton class, it will be ruined. A typed client is registered in a DI container with Transient, but if you DI to a Singleton class, the same instance will be reused all the time.

For example:

//Registration process to DI container
services.AddHttpClient();
services.AddSingleton<SomeSingleton>();

//Definition of SomeSingleton
class SomeSingleton
{
    private readonly HttpClient _httpClient; //When will I be released! ??

    public SomeSingleton(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    //abridgement
}

So

So, make sure that IHttpClientFactory is DI or managed by Scoped or Transient instead of Singleton.