Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

325
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda