Search code examples
c#asp.netasp.net-coredotnet-httpclient

How to use "TypedHttpClientFactory" with "AddHttpMessageHandler"?


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?


Solution

  • This is expected, as the ITypedHttpClientFactory documentation states:

    The default ITypedHttpClientFactory<TClient> uses type activation to create typed client instances. Typed client types are not retrieved directly from the IServiceProvider. See CreateInstance(IServiceProvider, Type, Object[]) for details.

    So, here's answer to your question:

    Typed client types are not retrieved directly from the IServiceProvider.