Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

324
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!