【问题标题】:Netcore 2.1 ServiceCollection adding generic typed HttpClients not resolving as expectedNet Core 2.1 IServiceCollection 添加泛型类型的 HttpClients 未按预期解析
【发布时间】:2019-02-18 13:27:34
【问题描述】:

我遇到了 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>();
    }
}

【问题讨论】:

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


    【解决方案1】:

    您无法根据泛型类型参数的泛型类型参数的差异进行解析。我可以推荐的最好的事情是创建具体的派生,然后您可以明确引用:

    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/");
    });
    

    【讨论】:

    • 刚试过这个哥们,但结果一样。我认为您可能是对的,尽管您尝试使用 httpclient 服务的泛型类型进行解析。
    • 抱歉,我意识到我没有明确说明您还需要注入这些派生类。
    • 我选择了一个抽象类,而不是试图使其成为一个通用接口,它可以正常工作
    • @JamesDev 你能分享一下你是怎么做到的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多