Home > database >  How to inject a NamedHttpClient to TypedHttpClient
How to inject a NamedHttpClient to TypedHttpClient

Time:01-18

In my .Net core application I have NamedHttpClient and I have a TypedHttpClient. I need to use the NamedClient as the default httpclient inside TypedHttpClient.

My configure services:

public static IServiceCollection ConfigureServiceOptions(this IServiceCollection services, IConfiguration config)
{
    IConfigurationSection serverSection = config.GetSection(nameof(ServerOptions));
    services.Configure<ServerOptions>(serverSection);
    
    
    //Named
    services.AddHttpClient("defaultHttpClient", client =>
    {

        client.BaseAddress = new System.Uri(dataServerSection.Get<ServerOptions>().ServerUrl);
        client.DefaultRequestHeaders.Add("Accept", "application/xml, */*");
        client.DefaultRequestHeaders.Add("User-Agent", "Server v1.0.0");
    });
    
}



//startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureServiceOptions(Configuration);
    
    //Adding Typed
    services.AddHttpClient<DataService>(); //I need to use defaultHttpClient as HttpClient Inside DataService
}

So far I found 3 ways to do this, not sure if there is any pitfall in any of the method

Way 1:

services.AddHttpClient<DataService>();

public class DataService
{
    private HttpClient Client { get;}
    public DataService(/*need to pass this otherwise cant resolve*/ HttpClient client, IHttpClientFactory factory)
    {
        Client = factory.CreateClient("defaultHttpClient");
    }
}

In Way 1 i need to have the additional HttpClient client parameter in the constructor. Otherwise the DataService is not resolved.

Way2:

services.AddTransient<DataService>( cfg =>
{
    var clientFactory = cfg.GetRequiredService<System.Net.Http.IHttpClientFactory>();
    var httpClient = clientFactory.CreateClient("defaultHttpClient");
    return new DataService(httpClient);
});

public class DataService
{
    private HttpClient Client { get;}
    public DataService(HttpClient client)
    {
        Client = client;
    }
}

Way 3:

services.AddTransient<DataService>();

public class DataService
{
    private HttpClient Client { get;}
    public DataService(IHttpClientFactory factory)
    {
        Client = factory.CreateClient("defaultHttpClient");
    }
}

I think Way2 and Way3 might be same. Not sure if there is any difference.

Can someone tell what is the recommended way ? or if there is any other way?

CodePudding user response:

Since you are not actually setting up the typed client for DataService the "Way 1" does not make much sense, it is basically "Way 3" but with extra steps.

"Way 2" make service code cleaner but will become cumbersome to maintain if new dependencies will be needed for it later.

"Way 3" is how using named HttpClient is shown in the docs so I would go with it.

  •  Tags:  
  • Related