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
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 HttpClient
s for you.
From the docs:
A new
HttpClient
instance is returned each timeCreateClient
is called on theIHttpClientFactory
. AnHttpMessageHandler
is created per named client. The factory manages the lifetimes of theHttpMessageHandler
instances.
IHttpClientFactory
pools theHttpMessageHandler
instances created by the factory to reduce resource consumption. AnHttpMessageHandler
instance may be reused from the pool when creating a newHttpClient
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 givenHttpClient
instance can't be used after callingDispose
.IHttpClientFactory
tracks and disposes resources used byHttpClient
instances.Keeping a single
HttpClient
instance alive for a long duration is a common pattern used before the inception ofIHttpClientFactory
. This pattern becomes unnecessary after migrating toIHttpClientFactory
.