我需要用 IHttpClientFactory 替换 HttpClient 的使用,以减少正在使用的套接字数量并避免套接字耗尽。
作为更好的方法,我想使用 IHttpClientFactory 并使用 Autofac 注册它,并且我还想确认 HttpClient 和 IHttpClientFactory 的使用之间的区别 - 如何知道我的实现是否正常工作?
我使用 IHttpClientFactory 的类的基本实现是这样的(其中一个类):
public class ImportHttpClient : IImportHttpClientAccessor
{
public HttpClient Client { get; }
public ImportHttpClient(IHttpClientFactory httpClientFactory)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Client = httpClientFactory.CreateClient();
Client.BaseAddress = new Uri(GlobalVariables.ImportServiceSettings.BaseUrl);
}
}
使用 Autofac 注册此类非常简单:
builder.RegisterType<ImportHttpClient>().As<IImportHttpClientAccessor>().InstancePerLifetimeScope();
但是,IHttpClientFactory 的注册仍然是个问题,也是使用 IHttpClientFactory 前后比较的一个测试。
经过大量研究和检查不同的资源,我设法找到了解决我的问题的方法。
在.NET 4.8中使用Autofac注册IHttpClientFactory是这样完成的:
builder.Register(ctx =>
{
var services = new ServiceCollection();
services.AddHttpClient();
var provider = services.BuildServiceProvider();
return provider.GetRequiredService<IHttpClientFactory>();
});
为了测试 HttpClient 与 IHttpClientFactory,我使用了 netstat,结果如下: 使用 HttpClient(无 HttpClientFactory):
如您所见,有很多打开的连接暂时不会自动关闭。
现在,相同的过程,但使用 IHttpClientFactory:
如您所见,我只得到了几个连接关闭的连接,而不是许多“挂在那里”的连接。
您应该使用
Autofac.Extensions.DependencyInjection
NuGet 包,而不是接受的答案。然后使用builder.Populate(...)
方法。
var services = new ServiceCollection();
// Example registration of a typed HttpClient
services.AddHttpClient<IMyClient, MyClient>();
// Additional registrations using extension methods go here
builder.Populate(services);
这可以避免每次将您的客户重新注册到新的服务集合中,并构建新的服务提供商。如果您要解析使用 Autofac 注册的依赖项,则该服务提供商也不会解析该依赖项。
另请参阅 https://autofac.readthedocs.io/en/latest/integration/netcore.html#quick-start 另一个例子。