提问者:小点点

解析不同的HttpClient


鉴于以下类:

public class HttpHelper
{
    private readonly HttpClient client;
    public HttpHelper(HttpClient client)
    {
        this.client = client;
    }
}

public class ServiceA
{
    private readonly HttpHelper helper;
    public ServiceA(HttpHelper helper)
    {
        this.helper = helper;
    }
 }

 public class ServiceB
 {
    private readonly HttpHelper helper;
    public ServiceB(HttpHelper helper)
    {
        this.helper = helper;
    }
}

和以下设置:

      sc.AddSingleton<ServiceA>()
         .AddHttpClient<HttpHelper>()
         .ConfigureHttpClient((sp, client) => { client.BaseAddress = new Uri("http://domainA"); });

      sc.AddSingleton<ServiceB>()
        .AddHttpClient<HttpHelper>()
        .ConfigureHttpClient((sp, client) => { client.BaseAddress = new Uri("http://domainB"); });

当我尝试解析ServiceA和ServiceB时,它们都得到一个具有相同URL的HttpClient。

我如何更改DI中的注册,使每个服务都得到正确的HttpClient注入?

TIA

/Søren


共2个答案

匿名用户

我宁愿做这样的事。

public class ServiceA
    { 
        private readonly HttpClient httpClient;

        public ServiceA(HttpClient httpClient)
        { 
            this.httpClient = httpClient;
        }
    }
    public class ServiceB
    {       
        private readonly HttpClient httpClient;
        public ServiceB(HttpClient httpClient)
        {            
            this.httpClient = httpClient;
        }
    }

和ConfigureService。

services.AddHttpClient<ServiceA>().ConfigureHttpClient(client =>
            {
                client.BaseAddress = new Uri("http://domainA");
            });
            services.AddHttpClient<ServiceB>().ConfigureHttpClient(client =>
            {
                client.BaseAddress = new Uri("http://domainB");
            });

注:

在你的情况下,有两件事是有问题的。

  1. AddSingletonfor ServiceA和ServiceB
  2. 由于AddHttpClient变为单例且只有一个get被启动,因此出现问题。

匿名用户

另一种方法是按命名工厂进行配置:

//configure your clients
services.AddHttpClient("clientName1", client => { 
   //configure
});

services.AddHttpClient("clientName2", client => { 
   //configure
});

//configure your services
services.AddScoped<ServiceA>(sp =>
    {
        var client = sp.GetRequiredService<IHttpClientFactory>()
            .CreateClient("clientName1");
        return new ServiceA(client);
    });

services.AddScoped<ServiceB>(sp =>
    {
        var client = sp.GetRequiredService<IHttpClientFactory>()
            .CreateClient("clientName2");
        return new ServiceB(client);
    });

这种方法的一个问题是,您需要明确定义服务A和B的解析器。

相关问题