Ant*_*ony 5 c# .net-core asp.net-core-2.0
HttpClientFactory提供以下扩展方法:
public static IHttpClientBuilder AddHttpClient<TClient>(this IServiceCollection services, string name)
Run Code Online (Sandbox Code Playgroud)
并且我创建了一个类型化的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
}
}
Run Code Online (Sandbox Code Playgroud)
我可以在程序的ServiceCollection中注册此自定义客户端,如下所示:
services.AddTransient<CustomAuthorizationInfoObject>();
services.AddHttpClient<CustomClient>("DefaultClient");
Run Code Online (Sandbox Code Playgroud)
然后,我可以注册此CustomClient的第二个实例,其中包含一些稍有更改的信息:
services.AddHttpClient<CustomClient>("AlternativeAuthInfo", (client) => {
client.DefaultRequestHeaders.Authorization = ...;
});
Run Code Online (Sandbox Code Playgroud)
在程序的其他地方,我现在想获取一个特定的名称CustomClient。这证明了障碍。
CustomClient只需通过CustomClient服务提供商的请求,我就能获得最后添加到服务中的任何一个。
IHttpClientFactory.CreateClient("AlternativeAuthInfo")例如,调用会返回HttpClient,因此我无法在CustomClient中访问其他方法,并且似乎没有其他任何方法可以帮助我。
因此,我该如何获取命名的CustomClient?还是我滥用通过原始扩展名来命名和引用类型化客户的机会?
Dav*_*ray 13
我看到有一个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);
Run Code Online (Sandbox Code Playgroud)