HttpClient注入单例
HttpClient inject into Singleton
假设我们有这样的代码:
services.AddHttpClient();
services.AddSingleton<IMyService, MyService>();
...
public class MyService : IMyService
{
public MyService(HttpClient httpClient)
{
}
}
有问题(可能是愚蠢的,但我只是想清楚一些事情):
- 它会使用
HttpClientFactory
创建 HttpClient
的实例吗?
- 我猜它使用了
HttpClientFactory
,但在那种情况下它会遇到 DNS 更改的问题吗?
尚不清楚 HttpMessageHandler
是否会针对单例服务进行管理,并且服务是否应该被限定范围以获取 HttpClientFactory
使用的所有好处。
- Will it use
HttpClientFactory
to create an instance of HttpClient
?
是的。默认 HttpClient
在 HttpClientFactory registration 期间注册为临时服务。
- I guess it uses
HttpClientFactory
but will it have issues with DNS changes in that case?
正确,它仍然会。当你将它注入到一个单例中时,这里的 HttpClient
只会被创建一次。为了利用 HttpClientFactory
的 HttpMessageHandler
池,您需要 HttpClient
为 short-lived。因此,为此您宁愿需要注入 IHttpClientFactory
本身并在需要时调用 CreateClient
。 (请注意 short-living HttpClient
仅适用于 HttpClientFactory
用法)。顺便说一句,在注入单例时切换到类型化客户端无济于事,HttpClient
最终仍将只创建一次,请参阅 https://github.com/dotnet/runtime/issues/64034.
此外,您实际上可以完全避免 HttpClientFactory
,并且仍然遵守 DNS 更改。为此,您可能将 static/singleton HttpClient
与 PooledConnectionLifetime
设置为一些合理的超时(例如,相同的 2 分钟 HttpClientFactory
)
services.AddSingleton(() => new HttpClient(
new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) }
));
假设我们有这样的代码:
services.AddHttpClient();
services.AddSingleton<IMyService, MyService>();
...
public class MyService : IMyService
{
public MyService(HttpClient httpClient)
{
}
}
有问题(可能是愚蠢的,但我只是想清楚一些事情):
- 它会使用
HttpClientFactory
创建HttpClient
的实例吗? - 我猜它使用了
HttpClientFactory
,但在那种情况下它会遇到 DNS 更改的问题吗?
尚不清楚 HttpMessageHandler
是否会针对单例服务进行管理,并且服务是否应该被限定范围以获取 HttpClientFactory
使用的所有好处。
- Will it use
HttpClientFactory
to create an instance ofHttpClient
?
是的。默认 HttpClient
在 HttpClientFactory registration 期间注册为临时服务。
- I guess it uses
HttpClientFactory
but will it have issues with DNS changes in that case?
正确,它仍然会。当你将它注入到一个单例中时,这里的 HttpClient
只会被创建一次。为了利用 HttpClientFactory
的 HttpMessageHandler
池,您需要 HttpClient
为 short-lived。因此,为此您宁愿需要注入 IHttpClientFactory
本身并在需要时调用 CreateClient
。 (请注意 short-living HttpClient
仅适用于 HttpClientFactory
用法)。顺便说一句,在注入单例时切换到类型化客户端无济于事,HttpClient
最终仍将只创建一次,请参阅 https://github.com/dotnet/runtime/issues/64034.
此外,您实际上可以完全避免 HttpClientFactory
,并且仍然遵守 DNS 更改。为此,您可能将 static/singleton HttpClient
与 PooledConnectionLifetime
设置为一些合理的超时(例如,相同的 2 分钟 HttpClientFactory
)
services.AddSingleton(() => new HttpClient(
new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) }
));