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?
AddHttpClient provides a way to centralize all the HTTP client configurations at one place. Named clients are a good choice when: The app requires many distinct uses of HttpClient . Many HttpClient s have different configuration.
A Typed Client is a class that accepts an HttpClient object (injected through its constructor) and uses it to call some remote HTTP service. For example: C# Copy.
By Kirk Larkin, Steve Gordon, Glenn Condron, and Ryan Nowak. An IHttpClientFactory can be registered and used to configure and create HttpClient instances in an app. IHttpClientFactory offers the following benefits: Provides a central location for naming and configuring logical HttpClient instances.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With