我有一个 ASP.Net Core 程序。我在
HttpClient
上添加了两个具有相同接口的 Startup.cs
类:
public class TypedClientA : ITypedClient
{
private readonly HttpClient _httpClient;
public class TypedClientA(HttpClient httpClient)
{
_httpClient = httpClient;
}
}
public class TypedClientB : ITypedClient
{
private readonly HttpClient _httpClient;
public class TypedClientB(HttpClient httpClient)
{
_httpClient = httpClient;
}
}
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpClient<ITypedClient, TypedClientA>(httpClient =>
{
httpClient.BaseAddress = new Uri("uri class A");
});
services.AddHttpClient<ITypedClient, TypedClientB>(httpClient =>
{
httpClient.BaseAddress = new Uri("uri class B");
});
...
}
然后我尝试在控制器中调用它们,但是每个键入的客户端中的
HttpClient
实例始终具有相同的 BaseAddress
,即使我在启动期间为每个实例填充了不同的基本 URL。
public class SomeController : Controller
{
private readonly IEnumerable<ITypedClient> _typedClients;
public OtherService(IEnumerable<ITypedClient> typedClients)
{
_typedClients = typedClients;
}
}
但是,如果我在
AddHttpClient
上没有界面的话 Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpClient<TypedClientA>(httpClient =>
{
httpClient.BaseAddress = new Uri("uri class A");
});
services.AddHttpClient<TypedClientB>(httpClient =>
{
httpClient.BaseAddress = new Uri("uri class B");
});
...
}
public class SomeController : Controller
{
private readonly TypedClientA _typedClientA;
private readonly TypedClientB _typedClientB;
public Class(TypedClientA typedClientA, TypedClientB typedClientB)
{
_typedClientA = typedClientA;
_typedClientB = typedClientB;
}
}
每个打字客户端上的
HttpClient
都会有自己的 BaseAddress
。
我做错了什么?我希望每个类型的客户端都具有相同的界面,但我也希望其中的每个
HttpClient
实例具有不同的 BaseAddress
。有什么解决办法吗?
.NET 依赖注入容器的工作方式是,当您为同一接口注册多个依赖项时,所有依赖项都将被注册,并且可以通过
IEnumerable<IInterface>
解决。因此,您的第一种方法不适用于您的情况。你的第二种方法很好。我认为没有任何理由在您的界面中显式注册它们。