首页 > 解决方案 > 解析不同的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

/索伦

标签: c#dependency-injectiondotnet-httpclient

解决方案


我宁愿做这样的事情。

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;
    }
}

在配置服务中。

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

笔记 :

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

  1. AddSingleton对于ServiceAServiceB
  2. AddHttpClient<HttpHelper>是问题,因为它变成单例并且只有一个被启动。

推荐阅读