The HttpClient factory already has a registered client with the type c#

Viewed 24

I need to inject HttpClient into multiple classes with the same interface

 service.AddTransient<IFooService, AFooService>();
            service.AddHttpClient<IFooService, AFooService>((serviceProvider, httpClient) => 
            {
            }).AddHttpMessageHandler<AzureDefaultCredentialsAuthorizationMessageHandler>();

however when I try and add more eg

 service.AddTransient<IFooService, BFooService>();
            service.AddHttpClient<IFooService, BFooService>((serviceProvider, httpClient) => 
            {
            }).AddHttpMessageHandler<AzureDefaultCredentialsAuthorizationMessageHandler>();

I get the error

The HttpClient factory already has a registered client with the type 'Project.IFooService'. Client types must be unique. Consider using inheritance to create multiple unique types with the same API surface.

I know the error is becuase I already have IFooService registered to inject a HttpClient, but I have no idea how to fix it.

any suggestions would be appriciated.

1 Answers

You can register typed HttpClient via instance:

services.AddHttpClient<AFooService>(// ... your setup);

And then if you need to "reabstract" those to interface (assuming you need them as a collection):

services.AddTransient<IFooService>(sp => sp.GetRequiredService<AFooService>());
Related