I have some AuthorizationHandler that I register with a typed client:
var clientFactory = services.BuildServiceProvider().GetRequiredService<IHttpClientFactory>();
services.AddHttpClient<TypedClient>()
.AddHttpMessageHandler(() =>
{
var authorization = new BearerAuthorization(clientFactory, clientId, clientSecret, authHost, token);
return new AuthorizationHandler(authorization);
});
When I get the "TypedClient" directly through the DI container, everything works fine and the AuthorizationHandler handler is called before the request, for example, like this:
_typedClient = serviceProvider.GetRequiredService<TypedClient>();
await _typedClient.SendRequest(); // OK
BUT. When trying to get this client from the ITypedHttpClientFactory factory, the handler stops being called, which gives an authorization error:
_httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();
_typedClientFactory = serviceProvider.GetRequiredService<ITypedHttpClientFactory<TypedClient>>();
using var client = _httpClientFactory.CreateClient();
using var typedClient = _typedClientFactory.CreateClient(client);
await typedClient.SendRequest(); // Fail
How do I get a typed client from the factory that will have the added handler called before the request?
2
Answers
This is expected, as the ITypedHttpClientFactory documentation states:
So, here’s answer to your question:
One way to solve this problem is to inject a named client into the typed client via the
ITypedHttpClientFactory
‘sCreateClient
method. Whenever you fetch a namedHttpClient
then it will retrieve it from the DI with all of itsDelegatingHandler
s.Here you can find a working example: https://dotnetfiddle.net/wC4Neg
Service registrations
DelegatingHandler
into the DI container firsttest
Client creations
ServiceCollection
IHttpClientFactory
and anITypedHttpClientFactory
service.CreateClient("test")
DelegatingHandler
TypedClient
instance via theITypedHttpClientFactory
by injecting the previously fetched namedHttpClient
Supporting structures