Lets say we have code like this:
services.AddHttpClient();
services.AddSingleton<IMyService, MyService>();
...
public class MyService : IMyService
{
public MyService(HttpClient httpClient)
{
}
}
There are questions (probably stupid, but I just want to clear some things):
HttpClientFactory to create an instance of HttpClient?HttpClientFactory but will it have issues with DNS changes in that case?It's not quite clear if HttpMessageHandlers will be managed for singleton services, and should service be scoped anyway to get all benefits of HttpClientFactory usage.
- Will it use
HttpClientFactoryto create an instance ofHttpClient?
Yes. A default HttpClient is registered as a transient service during HttpClientFactory registration.
- I guess it uses
HttpClientFactorybut will it have issues with DNS changes in that case?
Correct, it still would. As you inject it into a singleton, HttpClient here will be created only once. In order to make use of HttpClientFactory's HttpMessageHandler pooling, you'd need your HttpClients to be short-lived. So, for this you would rather need to inject IHttpClientFactory itself and call CreateClient when you need one. (Note that short-living HttpClients only apply to HttpClientFactory usage). BTW switching to a typed client will not help when injecting into a singleton, HttpClient will still end up being created only once, see https://github.com/dotnet/runtime/issues/64034.
Also, you can actually avoid HttpClientFactory entirely and still have DNS changes respected. For that you may have a static/singleton HttpClient with PooledConnectionLifetime set to some reasonable timeout (e.g. the same 2 minutes HttpClientFactory does)
services.AddSingleton(() => new HttpClient(
new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) }
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With