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?