Search code examples
c#dependency-injectiondotnet-httpclient

Resolving different HttpClient


Given the following classes:

public class HttpHelper
{
    private readonly HttpClient client;
    public HttpHelper(HttpClient client)
    {
        this.client = client;
    }
}

public class ServiceA
{
    private readonly HttpHelper helper;
    public ServiceA(HttpHelper helper)
    {
        this.helper = helper;
    }
 }

 public class ServiceB
 {
    private readonly HttpHelper helper;
    public ServiceB(HttpHelper helper)
    {
        this.helper = helper;
    }
}

and the following setup:

      sc.AddSingleton<ServiceA>()
         .AddHttpClient<HttpHelper>()
         .ConfigureHttpClient((sp, client) => { client.BaseAddress = new Uri("http://domainA"); });

      sc.AddSingleton<ServiceB>()
        .AddHttpClient<HttpHelper>()
        .ConfigureHttpClient((sp, client) => { client.BaseAddress = new Uri("http://domainB"); });

When I try to resolve ServiceA and ServiceB they both get an HttpClient with the same URL.

How do I change the registration in DI, so that each services get the correct HttpClient injected?

TIA

/Søren


Solution

  • Another way is to configure it by named factory:

    //configure your clients
    services.AddHttpClient("clientName1", client => { 
       //configure
    });
    
    services.AddHttpClient("clientName2", client => { 
       //configure
    });
    
    //configure your services
    services.AddScoped<ServiceA>(sp =>
        {
            var client = sp.GetRequiredService<IHttpClientFactory>()
                .CreateClient("clientName1");
            return new ServiceA(client);
        });
    
    services.AddScoped<ServiceB>(sp =>
        {
            var client = sp.GetRequiredService<IHttpClientFactory>()
                .CreateClient("clientName2");
            return new ServiceB(client);
        });
    

    An issue with this approach is that you explicitly need to define the resolver for Service A & B.