HttpClientFactory-通过名称获取命名的类型化客户端

时间:2018-09-06 10:23:12

标签: c# .net-core asp.net-core-2.0

HttpClientFactory提供以下扩展方法:

public static IHttpClientBuilder AddHttpClient<TClient>(this IServiceCollection services, string name)

并且我创建了一个如下类型的HttpClient:

public class CustomClient {

    public CustomClient(HttpClient client,
        CustomAuthorizationInfoObject customAuthorizationInfoObject) {
        /// use custom authorization info to customize http client
    }

    public async Task<CustomModel> DoSomeStuffWithClient() {
        /// do the stuff
    }

}

我可以按照以下步骤在程序的ServiceCollection中注册此自定义客户端:

services.AddTransient<CustomAuthorizationInfoObject>();
services.AddHttpClient<CustomClient>("DefaultClient");

然后我可以注册此CustomClient的第二个实例,并在其中进行一些稍作更改的信息:

services.AddHttpClient<CustomClient>("AlternativeAuthInfo", (client) => {
    client.DefaultRequestHeaders.Authorization = ...;
});

在程序的其他地方,我现在想获取一个名为CustomClient的特定名称。这就是障碍。

只需向服务提供商请求CustomClient,我就能获得最后添加到服务的CustomClient中的任何一个。

例如,调用IHttpClientFactory.CreateClient("AlternativeAuthInfo")会返回一个HttpClient,因此我无法在CustomClient中访问其他方法,并且似乎没有其他方法可以帮助我。

因此,我该如何获取命名的CustomClient?还是我滥用通过原始扩展方法命名和引用类型化客户的机会?

1 个答案:

答案 0 :(得分:3)

我看到有一个ITypedHttpClientFactory<>接口,可以将常规HttpClient包装在键入的接口中。不是亲自使用它,而是丢失的那一块吗?

例如

/// grab the named httpclient
var altHttpClient = httpClientFactory.CreateClient("AlternativeAuthInfo");

/// get the typed client factory from the service provider
var typedClientFactory = serviceProvider.GetService<ITypedHttpClientFactory<CustomClient>>();

/// create the typed client
var altCustomClient = typedClientFactory.CreateClient(altHttpClient);