对新 ihttpfactory 中 httpclient 的生命周期感到困惑

Puzzled by the lifetime of the httpclient in the new ihttpfactory

从规范为单例 httpclient 的代码重构到新的 ihttpfactory 我对 httpClient 的生命周期感到非常困惑:

The typed client is registered as transient with DI. [Typed clients]

这意味着我以前依赖 httpclient 的所有单例服务现在都将效仿 [即是短暂的]。我找不到关于此设计选择的支持文档?现在这不会对性能造成伤害,因为我们必须使所有依赖关系图都成为瞬态的吗?

Google "typed httpclient transient" 是你的朋友:https://www.stevejgordon.co.uk/ihttpclientfactory-patterns-using-typed-clients-from-singleton-services

简而言之,不是直接注入和使用类型化 HttpClient,而是创建一个依赖于 IServiceProvider 的工厂,使用该服务提供者的方法 return 类型化 HttpClient 的实例,并注入那个工厂。然后每次需要类型化 HttpClient 的实例时调用工厂的创建方法。服务提供商为您完成所有范围管理。

换句话说,不是下面的:

services.AddHttpClient<IMyHttpClient, MyHttpClient>();
services.AddScoped<IDependsOnHttpClient, DependsOnHttpClient>();

...

public class DependsOnHttpClient : IDependsOnHttpClient
{
    private readonly IMyHttpClient _httpClient;

    public DependsOnHttpClient(IMyHttpClient httpClient)
        => _httpClient = httpClient;

    public async Task DoSomethingWithHttpClientAsync()
        => _httpClient.GetAsync("https://foo.bar");
}

你写:

services.AddHttpClient<IMyHttpClient, MyHttpClient>();
services.AddSingleton<IMyHttpClientFactory, MyHttpClientFactory>();
services.AddSingleton<IDependsOnHttpClient, DependsOnHttpClient>();

...

public class MyHttpClientFactory : IMyHttpClientFactory
{
    private readonly IServiceProvider _serviceProvider;

    public MyHttpClientFactory(IServiceProvider serviceProvider)
        => _serviceProvider = serviceProvider;

    public IMyHttpClient CreateClient()
        => _serviceProvider.GetRequiredService<IMyHttpClient>();
}

public class DependsOnHttpClient : IDependsOnHttpClient
{
    private readonly IMyHttpClientFactory _httpClientFactory;

    public DependsOnHttpClient(IMyHttpClientFactory httpClientFactory)
        => _httpClientFactory = httpClientFactory;

    public async Task DoSomethingWithHttpClientAsync()
    {
         var httpClient = _httpClientFactory.CreateClient();

         return await _httpClient.GetAsync("https://foo.bar");
    }
}

此时您可能想知道“与仅注入 IHttpClientFactory 并调用其方法相比,通过编写所有这些代码我可以获得什么”,老实说,我不确定答案。也许使用 Roslyn 源代码生成器,我们将能够为它们生成类型化的 HttpClient 和工厂。

文档中提到了性能 here

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

通过引入 IhttpClientFactory

以某种方式解决了这个问题

The preceding approaches solve the resource management problems that IHttpClientFactory solves in a similar way