简体   繁体   English

HttpClient 工厂已经有一个类型为 c# 的注册客户端

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

I need to inject HttpClient into multiple classes with the same interface我需要将 HttpClient 注入到具有相同接口的多个类中

 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.我知道错误是因为我已经注册了 IFooService 以注入 HttpClient,但我不知道如何修复它。

any suggestions would be appriciated.任何建议都会被采纳。

You can register typed HttpClient via instance:您可以通过实例注册类型化的HttpClient

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>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM