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 byHttpClient
s for you.From the docs: