.Net IHttpClientFactory 与 Singleton 的结合使用

.Net IHttpClientFactory usage with Singleton

因此,如果我通过 DI 将 class 注册为单个实例(单例),然后将 IHttpClientFactory 注入 class。

 class MyService : IMyService
    {
        private readonly IHttpClientFactory _clientFactory;

        public MyService(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }
        public async Task Call()
        {
            var client = _clientFactory.CreateClient("MyClient");
            await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://test.com"));
        }
    }

在每次调用函数 Call 时,我使用 _clientFactory.CreateClient 创建一个新客户端是否正确?或者我应该在工厂的构造函数中创建一个客户端,然后在每个函数调用中重新使用它?

感谢

每次调用MyService.Call()方法都可以创建一个客户端。完成后无需处理它。 IHttpClientFactory 为您管理 HttpClient 所使用的资源。

来自 the docs:

A new HttpClient instance is returned each time CreateClient is called on the IHttpClientFactory. An HttpMessageHandler is created per named client. The factory manages the lifetimes of the HttpMessageHandler instances.

IHttpClientFactory pools the HttpMessageHandler instances created by the factory to reduce resource consumption. An HttpMessageHandler instance may be reused from the pool when creating a new HttpClient instance if its lifetime hasn't expired.

...

HttpClient instances can generally be treated as .NET objects not requiring disposal. Disposal cancels outgoing requests and guarantees the given HttpClient instance can't be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances.

Keeping a single HttpClient instance alive for a long duration is a common pattern used before the inception of IHttpClientFactory. This pattern becomes unnecessary after migrating to IHttpClientFactory.