如何将多个HttpClient参数传递/注入到类型化的HttpClientClass中?

时间:2019-03-25 15:48:29

标签: c# asp.net-core dependency-injection .net-core dotnet-httpclient

我想在这里Microsoft docs注册一个类型化的HttpClient。 基本上,方法应该是

services.AddHttpClient();

通常,这些类的模式仅将HttpClient类作为参数接收,并且您可以实现调用端点的逻辑。就我而言,我需要在MyHttpClient中使用2个HttpClient,一个ping端点,另一个与IdentityProvider对话以发现refreshEndpoints来刷新我的cookie。

public class MyHttpClient : IMyHttpClient
{
    public MyHttpClient (HttpClient httpClient, 
                         HttpClient refreshHttpClient)
    {
    }
}

如果我尝试从控制器解析IMyHttpClient,则会收到一条错误消息,提示它无法解析HttpClient。

在第43行AddHttpClient的GitHub代码中,您可以看到正在调用 DefaultTypedHttpClientFactory。 如果转到DefaultTypedHttpClientFactory implementation的实现,您会注意到这是一个通用类型。而且,当它调用CreateClient时,只会在第39行将一个参数传递给构造函数。

我在这里看到的唯一解决方法是不创建一个类型化的客户端,并注册一个接收IHttpClientFactory的普通类,并动态地创建和配置我的客户端,而不是输入类型。 还有其他想法吗?

1 个答案:

答案 0 :(得分:1)

不能。您要么需要注入另一个服务层,要么直接IHttpClientFactory

另一项服务

public class MyRefreshClient
{
    private readonly HttpClient _httpClient;

    public MyRefreshClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    ...
}

public class MyHttpClient : IMyHttpClient
{
    private readonly HttpClient _httpClient;
    private readonly MyRefreshClient _refreshClient;

    public MyHttpClient(HttpClient httpClient, MyRefreshClient refreshClient)
    {
        _httpClient = httpClient;
        _refreshClient = refreshClient;
    }
}

然后:

services.AddHttpClient<MyRefreshClient>(c => { ... });
services.AddHttpClient<MyHttpClient>(c => { ... });

注入IHttpClientFactory(并使用命名的客户端)

public class MyHttpClient : IMyHttpClient
{
    private readonly HttpClient _httpClient;
    private readonly HttpClient _refreshClient;

    public MyHttpClient(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient("MyHttpClient");
        _refreshClient = httpClientFactory.CreateClient("MyRefreshClient");
    }
}

然后:

services.AddHttpClient("MyHttpClient", c => { ... });
services.AddHttpClient("MyRefreshClient", c=> { ... });