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?

1

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.

2

One way to solve this problem is to inject a named client into the typed client via the ITypedHttpClientFactory‘s CreateClient method. Whenever you fetch a named HttpClient then it will retrieve it from the DI with all of its DelegatingHandlers.

Here you can find a working example: https://dotnetfiddle.net/wC4Neg

Service registrations

ServiceCollection collection  = new();
collection.AddTransient<TestDelegatingHandler>();
collection.AddHttpClient();
collection.AddHttpClient<ITypedClient, TypedClient>("test")
    .AddHttpMessageHandler(sp => sp.GetService<TestDelegatingHandler>());
  • Here we register a dummy DelegatingHandler into the DI container first
  • Then we register the default HttpClient factories
  • Finally we register a typed client which is named test
    • Here we add the MessageHandler to the named client

Client creations

ServiceProvider provider = collection.BuildServiceProvider();
IHttpClientFactory namedFactory = provider.GetRequiredService<IHttpClientFactory>();
ITypedHttpClientFactory<TypedClient> typedFactory  = provider.GetRequiredService<ITypedHttpClientFactory<TypedClient>>();

HttpClient namedClient = namedFactory.CreateClient("test");
TypedClient typedClient = typedFactory.CreateClient(namedClient); 
  • First we build the ServiceCollection
  • Then we retrieve an IHttpClientFactory and an ITypedHttpClientFactory service
  • Thirdly we fetch the named client .CreateClient("test")
    • This client is decorated with the dummy DelegatingHandler
  • Finally we create a TypedClient instance via the ITypedHttpClientFactory by injecting the previously fetched named HttpClient

Supporting structures

public interface ITypedClient
{
    Task GetAsync();
}

public class TypedClient: ITypedClient
{
    private readonly HttpClient _client;
    public TypedClient(HttpClient client) => _client = client;
    
    public async Task GetAsync() => await _client.GetAsync("http://stackoverflow.com");
}

public class TestDelegatingHandler: DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        "Hello".Dump();
        return await base.SendAsync(request, cancellationToken);
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật