.Net IHttpClientFactory usage with Singleton

924 Views Asked by At

So if I have a class registered through DI as a Single Instance (Singleton) and I inject the IHttpClientFactory inside the class.

 class MyService : IMyService
    {
        private readonly IHttpClientFactory _clientFactory;

        public MyService(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }
        public async Task Call()
        {
            var client = _clientFactory.CreateClient("MyClient");
            await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://test.com"));
        }
    }

Is it correct that on every call to the function Call I create a new client using the _clientFactory.CreateClient? or should I create one client in the constructor wth the factory and then re-use that for every function call?

thx

1

There are 1 best solutions below

0
On BEST ANSWER

You can create a client each time you call MyService.Call() method. No need to dispose it once you're done with it. IHttpClientFactory manages the resources used by HttpClients for you.

From the docs:

A new HttpClient instance is returned each time CreateClient is called on the IHttpClientFactory. An HttpMessageHandler is created per named client. The factory manages the lifetimes of the HttpMessageHandler instances.

IHttpClientFactory pools the HttpMessageHandler instances created by the factory to reduce resource consumption. An HttpMessageHandler instance may be reused from the pool when creating a new HttpClient instance if its lifetime hasn't expired.

...

HttpClient instances can generally be treated as .NET objects not requiring disposal. Disposal cancels outgoing requests and guarantees the given HttpClient instance can't be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances.

Keeping a single HttpClient instance alive for a long duration is a common pattern used before the inception of IHttpClientFactory. This pattern becomes unnecessary after migrating to IHttpClientFactory.