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?或者我是否滥用机会通过原始扩展方法命名和引用类型化客户端?
我看到有一个ITypedHttpClientFactory<>
界面可以包装常规HttpClient
在一个类型。没有亲自使用它,但这是缺少的一块?
EG
/// 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);