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

123
Visualizações
HttpClient properties not being passed with DI

I'm working on an ASP.NET Core 5.0 project which has a service that accesses an API. Based on the code below, I'd expect the HttpClient supplied to ToornamentService's constructor to contain the declared BaseAddress and API key header.

However, when debugging, I noticed that the HttpClient never has either of those. BaseAdress is null, and the header is missing. I've tried using an IHttpClientFactory instead of the typed client, but I end up with the same result.

What am I doing wrong?

ConfigureServices Method:

public void ConfigureServices(IServiceCollection services)
    {
        //Omitted for brevity
        services.AddHttpClient<ToornamentService>(c =>
        {
            c.BaseAddress = new Uri("https://api.toornament.com/");
            c.DefaultRequestHeaders.Add("X-Api-Key", Configuration["Toornament:ApiKey"]);
        });

        services.AddTransient<ToornamentService>();
    }

ToornamentService class:

public ToornamentService(HttpClient client)
    {
        Client = client; // client.BaseAddress here is null
    }
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Remove this line: services.AddTransient<ToornamentService>();

When you call AddHttpClient, it injects the service for you as transient.

So what you are doing is injecting it twice. And since your transient injection is the last injection, that takes precedence over the AddHttpClient injection.

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