gpt4 book ai didi

c# - 解析不同的HttpClient

转载 作者:行者123 更新时间:2023-12-05 09:34:21 25 4
gpt4 key购买 nike

给定以下类:

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 中的注册,以便每个服务都能注入(inject)正确的 HttpClient?

TIA

/索伦

最佳答案

我宁愿做这样的事情。

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. AddSingleton对于 ServiceAServiceB
  2. AddHttpClient<HttpHelper>这是个问题,因为它变成了单例,并且只有一个被启动。

关于c# - 解析不同的HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66722715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com