Search code examples
c#.net-core

HttpClient and IHttpClientFactory inheritance logic


I am creating a client like this in Startup.cs class.

services.AddHttpClient("myClient", client => 
{
  client.BaseAddress = new Uri("https://test.com");
});

Then I have a client file Client.cs

protected readonly HttpClient httpClient;
public Client(HttpClient httpClient)
{
  this.httpClient = httpClient;
}

Now, when I extend my Client class in ServiceClass.cs:

private readonly HttpClient _myClient;
public ServiceClass(IHttpClientFactory httpClientFactory) : base(//What should I pass here?)
{
  _myClient = httpClientFactory.CraeteClient("myClient");
}

I am not sure what object should I pass here, or maybe my code structure is incorrect. Please help!


Solution

  • Remove the _myClient field entirely since you have a protected field httpClient and instead let the base constructor handle it:

    public ServiceClass(IHttpClientFactory httpClientFactory) : 
    base(httpClientFactory.CreateClient("myClient")) 
    {}
    

    Code presumes you aren't looking for two different HttpClient members.