Search code examples
c#.net-coreasp.net-core-2.0

HttpClientFactory - Get a named, typed client by its name


HttpClientFactory offers the following extension method:

public static IHttpClientBuilder AddHttpClient<TClient>(this IServiceCollection services, string name)

and I've created a typed HttpClient as follows:

public class CustomClient {

    public CustomClient(HttpClient client,
        CustomAuthorizationInfoObject customAuthorizationInfoObject) {
        /// use custom authorization info to customize http client
    }

    public async Task<CustomModel> DoSomeStuffWithClient() {
        /// do the stuff
    }

}

I can register this custom client in the program's ServiceCollection as follows:

services.AddTransient<CustomAuthorizationInfoObject>();
services.AddHttpClient<CustomClient>("DefaultClient");

I can then register a second instance of this CustomClient with some slightly altered info in it:

services.AddHttpClient<CustomClient>("AlternativeAuthInfo", (client) => {
    client.DefaultRequestHeaders.Authorization = ...;
});

Elsewhere in the program I now want to get a specific named CustomClient. This is proving the obstacle.

I can get whichever CustomClient was added to services last simply by requesting CustomClient from the service provider.

Calling IHttpClientFactory.CreateClient("AlternativeAuthInfo"), for example, returns an HttpClient, so I can't access the extra method in CustomClient, and there don't appear to be any other methods there that help me.

How therefore do I go about getting a named CustomClient? Or am I misusing the opportunity to name and reference a typed client via the original extension method?


Solution

  • I see that there is a ITypedHttpClientFactory<> interface that can wrap a regular HttpClient in a typed one. Not used it personally, but is that the missing piece?

    e.g.

    /// grab the named httpclient
    var altHttpClient = httpClientFactory.CreateClient("AlternativeAuthInfo");
    
    /// get the typed client factory from the service provider
    var typedClientFactory = serviceProvider.GetService<ITypedHttpClientFactory<CustomClient>>();
    
    /// create the typed client
    var altCustomClient = typedClientFactory.CreateClient(altHttpClient);