Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient inject into Singleton

Tags:

c#

.net-core

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):

  1. Will it use HttpClientFactory to create an instance of HttpClient?
  2. I guess it uses 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.

like image 337
Alexey Klipilin Avatar asked Feb 26 '26 01:02

Alexey Klipilin


1 Answers

  1. Will it use HttpClientFactory to create an instance of HttpClient?

Yes. A default HttpClient is registered as a transient service during HttpClientFactory registration.

  1. I guess it uses HttpClientFactory but 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) }
));
like image 137
Natalia Kondratyeva Avatar answered Feb 27 '26 13:02

Natalia Kondratyeva