C#C
C#3y ago
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
  }
}

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
   }
}

like why work with local variable and invoke CreateClient() multiple times?
Was this page helpful?