c# - Netcore 2.1 ServiceCollection 添加通用类型的 HttpClients 未按预期解析
问题描述
我遇到了 Netcore 2.1 向 ServiceCollection 添加多个通用类型的HttpClient的问题。这没有按预期工作,它给了我奇怪的结果。
考虑我的测试
var services = new ServiceCollection();
services.AddHttpClient<IHttpGenericClientFactory<test1>, HttpGenericClientFactory<test1>>(client =>
{
client.BaseAddress = new Uri("https://test1.com/");
});
services.AddHttpClient<IHttpGenericClientFactory<test2>, HttpGenericClientFactory<test2>>(client =>
{
client.BaseAddress = new Uri("https://test2.com/");
});
现在尝试解决每个服务时
var provider = services.BuildServiceProvider();
var service1 = provider.GetService<IHttpGenericClientFactory<test1>>();
var service2 = provider.GetService<IHttpGenericClientFactory<test2>>();
当我检查service1.BaseAddress值是“ https://test2.com/ ”并且service2.BaseAddress也是“ https://test2.com/ ”。无论我尝试了什么,该服务总是解析或引用已添加的最后一个通用类型服务。这是框架中的错误吗?任何人都知道为什么这不能正常工作?这绝对与通用类型的 http 客户端有关。
我的通用类和接口
public interface IHttpGenericClientFactory<out T3>
{
HttpClient HttpClient { get; set; }
Task<T1> Get<T1, T2>(T2 request, string path);
}
public class HttpGenericClientFactory<T3> : IHttpGenericClientFactory<T3>
{
public HttpClient HttpClient { get; set; }
public HttpGenericClientFactory(HttpClient httpClient) => this.HttpClient = httpClient;
public async Task<T1> Get<T1,T2>(T2 request, string path)
{
var response = await HttpClient.GetAsync(path);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<T1>();
}
}
解决方案
您无法根据泛型类型参数的泛型类型参数的差异进行解析。我可以推荐的最好的事情是创建具体的派生,然后您可以明确引用:
public class Test1ClientFactory : HttpGenericClientFactory<Test1> {}
public class Test2ClientFactory : HttpGenericClientFactory<Test2> {}
然后:
services.AddHttpClient<Test1ClientFactory>(client =>
{
client.BaseAddress = new Uri("https://test1.com/");
});
services.AddHttpClient<Test2ClientFactory>(client =>
{
client.BaseAddress = new Uri("https://test2.com/");
});
推荐阅读
- javascript - 如何将动态(变化的)字符串分成两个不同的部分?
- bigcommerce - 任何人都可以帮助我用 bigcommerce CLI 纠正错误吗
- powershell - 您可以使用 PSCredential 对象运行 quser 吗?
- python - 在 try except 语句中调用相同的函数
- javascript - TimeZone 选项在 Intl.DateTimeFormat() 中究竟做了什么
- c - 有没有办法在 O(N) 中按字典顺序对字符串数组进行排序?
- vue.js - nuxt.js 中的 net::ERR_INCOMPLETE_CHUNKED_ENCODING 200(OK)
- java - 按天更新 postgresql 中的兴趣值
- spring-mvc - 一次模拟两个用户来测试一个 2 人游戏?
- powershell - 使用凭据时出现 Powershell Start-Process 错误