I'm looking into using IHttpClientFactory for calling external APIs in my asp.net core app. I've seen a few examples where the client factory is created in the constructor of the service's class. Then the methods of that class, call that client factory to generate an instance of HttpClient to make Http requests. Like the following sample code:
public class MyTransientService: IMyService
{
private readonly IHttpClientFactory _clientFactory;
public MyTransientService(
IHttpClientFactory clientFactory
)
{
_clientFactory = clientFactory;
}
public async Task<MyData> GetData()
{
//construct the request
var httpClient = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
...
}
}
If the service is registered as transient in startup.cs, wouldn't a new instance of HttpClientFactory be generated each time that the service is called? A new HttpClientFactory per request? So wouldn't the following be a more efficient way to use the factory?
public class MyTransientService: IMyService
{
private readonly HttpClient _client;
public MyTransientService(
HtpClient client
)
{
_client = client;
}
public async Task<MyData> GetData()
{
Uri uri = new Uri(StaticUtils.AddQueryString(url, props));
var response = await _client.SendAsync(request);
...
}
}