ASP.Net Core 2.1 和 IHttpClientFactory 中的 Flurl 客户端生命周期

Flurl client lifetime in ASP.Net Core 2.1 and IHttpClientFactory

Flurl 表示建议使用单例客户端模式:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

但是自从 Asp.Net Core 2.1 以来就有了 updated rules for HttpClient lifetime in Net Core 2.1

When you use the HttpClientFactory to request a HttpClient, you do in fact get a new instance each time, which means we don’t have to worry about mutating it’s state. This HttpClient may (or may not) use an existing HttpClientHandler from the pool and therefore use an existing open connection.

如何修改 Flurl 以在后台使用 IHttpClientFactory?我应该创建自定义 Flurl 的 settings.HttpClientFactory 并通过 MS IHttpClientFactory 创建 HttpClient 吗?

首先,应该注意的是,MS 的新 HttpClientFactory 旨在与 ASP.NET Core 2.1 及其内置的 DI 容器结合使用。如果您没有将 FlurlClients 注入控制器或服务 classes,而是像这样使用 Flurl:

await url.GetJsonAsync();

那么它甚至都不相关。您应该 而不是 实施 Flurl's IHttpClientFactory to use MS's. It doesn't have the proper context to use the DI container and you'll end up resorting to service location, which is an anti-pattern. Those new socket pooling features you want to take advantage of actually live at a lower level:System.Net.Http.SocketsHttpHandler。 Flurl 默认使用 HttpClientHander 作为其消息处理程序,但幸运的是,它已在 .NET Core 2.1 中重写,默认将其所有工作推迟到 SocketsHttpHandler。换句话说,如果您在 .NET Core 2.1 应用程序中使用 Flurl,那么您已经获得了 MS 一直致力于开发的所有新套接字管理功能

如果您 在 ASP.NET 核心 2.1 应用程序中明确使用 FlurlClient,作为 HttpClient 的替代品,并且会喜欢将它注入您的 classes 同时利用 MS 的 HttpClientFactory 必须提供的功能,我建议完全按照 MS 的规定在 ConfigureServices 中设置 HttpClientFactory,并且当您需要 FlurlClient 实例时,请使用采用 HttpClient 实例的构造函数。例如,当使用类型化客户端模式时,您的服务 class 可能如下所示:

public class MyService
{
    private readonly IFlurlClient _flurlClient;

    public MyService(HttpClient httpClient)
    {
        _flurlClient = new FlurlClient(httpClient);
    }
}