调用包含两个不同基地址的多个 httpclient
Calling multiple httpclient that contain two different base address
我已阅读 named clients and typed clients 以实现我的最终目标。但是,我仍然不明白我需要如何实施或。我有一个 blazor 服务器端项目,在 startup.cs 文件中我将其设置为
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("http://localhost:36626") });
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5443") });
我知道如果我这样做,第一个的基地址将被完全覆盖,并且由于第二个基地址而不再是设置的基地址。 我将如何着手完成这项工作,以便我有两个独立的 httpclients,它们将有两个独立的基地址,而不必因为最近的代码行而丢失一个?
如文档中所述,主要区别在于您将如何通过依赖注入获取实例。
使用 Named Client 你需要注入工厂然后通过字符串获取客户端。
var client = _clientFactory.CreateClient("github");
使用 Typed Client 您可以将所需的客户端作为类型注入。
//GitHubService encapsulate an HTTP client
public TypedClientModel(GitHubService gitHubService)
{
_gitHubService = gitHubService;
}
他们都给出了解决您问题的方法。选择更多的是你对每个依赖注入方法的适应程度。我个人更喜欢 Typed 客户端。
我已阅读 named clients and typed clients 以实现我的最终目标。但是,我仍然不明白我需要如何实施或。我有一个 blazor 服务器端项目,在 startup.cs 文件中我将其设置为
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("http://localhost:36626") });
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5443") });
我知道如果我这样做,第一个的基地址将被完全覆盖,并且由于第二个基地址而不再是设置的基地址。 我将如何着手完成这项工作,以便我有两个独立的 httpclients,它们将有两个独立的基地址,而不必因为最近的代码行而丢失一个?
如文档中所述,主要区别在于您将如何通过依赖注入获取实例。
使用 Named Client 你需要注入工厂然后通过字符串获取客户端。
var client = _clientFactory.CreateClient("github");
使用 Typed Client 您可以将所需的客户端作为类型注入。
//GitHubService encapsulate an HTTP client
public TypedClientModel(GitHubService gitHubService)
{
_gitHubService = gitHubService;
}
他们都给出了解决您问题的方法。选择更多的是你对每个依赖注入方法的适应程度。我个人更喜欢 Typed 客户端。