Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

327
Vistas
HttpClient inject into Singleton

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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

  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) }
));
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda