我遇到了 Netcore 2.1 向 ServiceCollection 添加多個(gè)通用類型的HttpClient的問題。這沒有按預(yù)期工作,它給了我奇怪的結(jié)果??紤]我的測(cè)試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/");});現(xiàn)在嘗試解決每個(gè)服務(wù)時(shí)var provider = services.BuildServiceProvider();var service1 = provider.GetService<IHttpGenericClientFactory<test1>>();var service2 = provider.GetService<IHttpGenericClientFactory<test2>>();當(dāng)我檢查service1.BaseAddress值是“ https://test2.com/ ”并且service2.BaseAddress也是“ https://test2.com/ ”。無論我嘗試了什么,該服務(wù)總是解析或引用已添加的最后一個(gè)通用類型服務(wù)。這是框架中的錯(cuò)誤嗎?任何人都知道為什么這不能正常工作?這絕對(duì)與通用類型的 http 客戶端有關(guān)。我的通用類和接口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>(); }}
1 回答

慕后森
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
您無法根據(jù)泛型類型參數(shù)的泛型類型參數(shù)的差異進(jìn)行解析。我可以推薦的最好的事情是創(chuàng)建具體的推導(dǎo),然后您可以明確引用:
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/");
});
- 1 回答
- 0 關(guān)注
- 190 瀏覽
添加回答
舉報(bào)
0/150
提交
取消