总结
-
HttpClient 只能注入到 Typed 客户端
- 其他用途需要
IHttpClientFactory
- 在这两种情况下,
HttpClientMessageHandler 的生命周期都由框架管理,因此您不必担心(错误地)处置 HttpClients。
示例
为了直接注入HttpClient,你需要注册一个特定的Typed服务来接收客户端:
services.AddHttpClient<GithubClient>(c => c.BaseAddress = new System.Uri("https://api.github.com"));
现在我们可以将其注入到 typed GithubClient
public class GithubClient
{
public GithubClient(HttpClient client)
{
// client.BaseAddress is "https://api.github.com"
}
}
您不能在AnotherClient 中注入HttpClient,因为它没有输入 到AnotherClient
public class AnotherClient
{
public AnotherClient(HttpClient client)
{
// InvalidOperationException, can't resolve HttpClient
}
}
但是,您可以:
1. 注入IHttpClientFactory并调用CreateClient()。此客户端将 BaseAddress 设置为 null。
2. 或者将AnotherClient 配置为不同类型的客户端,例如使用不同的BaseAdress。
更新
根据您的评论,您正在注册一个命名客户。它仍然是从 IHttpClientFactory.CreateClient() 方法解决的,但您需要传递客户端的“名称”
注册
services.AddHttpClient("githubClient", c => c.BaseAddress = new System.Uri("https://api.github.com"));
用法
// note that we inject IHttpClientFactory
public HomeController(IHttpClientFactory factory)
{
this.defaultClient = factory.CreateClient(); // BaseAddress: null
this.namedClient = factory.CreateClient("githubClient"); // BaseAddress: "https://api.github.com"
}