© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
157 replies
Thalnos

✅ DI with HttpClient / HttpClientFactory

The docs show the basic usage of HttpClientFactory with DI as follows:
public class SomeService{
  private IHttpClientFactory _httpFactory;
  public SomeService(IHttpClientFactory httpFactory){
    _httpFactory = httpFactory;
  }
  public void Method1(){
    var client = _httpFactory.CreateClient();
    //use client to do something
  }
  public void Method2(){
    var client = _httpFactory.CreateClient();
    //use client to do something
  }
}
public class SomeService{
  private IHttpClientFactory _httpFactory;
  public SomeService(IHttpClientFactory httpFactory){
    _httpFactory = httpFactory;
  }
  public void Method1(){
    var client = _httpFactory.CreateClient();
    //use client to do something
  }
  public void Method2(){
    var client = _httpFactory.CreateClient();
    //use client to do something
  }
}

I wonder why not do something like this instead:
public class SomeService{
   private HttpClient _client;
   public SomeService(IHttpClientFactory httpFactory){
      _client = httpFactory.CreateClient();
   }
   public void Method1(){
      //use client to do something
   }
   public void Method1(){
      //use client to do something
   }
}
public class SomeService{
   private HttpClient _client;
   public SomeService(IHttpClientFactory httpFactory){
      _client = httpFactory.CreateClient();
   }
   public void Method1(){
      //use client to do something
   }
   public void Method1(){
      //use client to do something
   }
}

like why work with local variable and invoke CreateClient() multiple times?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

HttpClient DI or USING()
C#CC# / help
4y ago
HttpClientFactory and Keep-Alive
C#CC# / help
2y ago
HttpClientFactory Content is not defined
C#CC# / help
4y ago
Setting BaseURI for named HttpClient in DI not including trailing string
C#CC# / help
3y ago