问题描述
Flurl指出推荐使用单例客户端模式:
Flurl states that using singleton client is recommended pattern:
但是自从Asp.Net Core 2.1以来, Net中HttpClient生存期的更新规则核心2.1 .
But since Asp.Net Core 2.1 there are updated rules for HttpClient lifetime in Net Core 2.1.
如何修改Flurl以在后台使用IHttpClientFactory?我应该创建自定义Flurl的settings.HttpClientFactory
,然后通过MS IHttpClientFactory创建HttpClient吗?
How to modify Flurl to use IHttpClientFactory under hood? Should I create custom Flurl's settings.HttpClientFactory
and there create HttpClient through MS IHttpClientFactory?
推荐答案
首先,应该注意,MS的新HttpClientFactory
旨在与ASP.NET Core 2.1及其内置的DI容器结合使用.如果您没有将FlurlClient
注入到控制器或服务类中,而是使用Flurl,如下所示:
First, it should be noted that MS's new HttpClientFactory
is intended to be used in conjunction with ASP.NET Core 2.1 and its built-in DI container. If you're not injecting FlurlClient
s into controllers or service classes, and are instead using Flurl like this:
await url.GetJsonAsync();
那么它甚至不相关.您应该不实施 Flurl的IHttpClientFactory 以使用MS.它没有使用DI容器的适当上下文,您最终将诉诸服务位置,这是一种反模式.您想利用的这些新套接字池功能实际上处于较低级别: System.Net.Http.SocketsHttpHandler
. Flurl默认使用HttpClientHander
作为其消息处理程序,但幸运的是,在.NET Core 2.1中已对其进行了重写,以默认将其所有工作推迟到SocketsHttpHandler
进行.换句话说,如果您在.NET Core 2.1应用程序中使用Flurl,则已经获得了MS一直在使用的所有新套接字管理工具.
then it's not even relevant. You should not implement 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 uses HttpClientHander
as its message handler by default, but luckily that's been rewritten in .NET Core 2.1 to defer all of its work to SocketsHttpHandler
by default. In other words, if you're using Flurl in a .NET Core 2.1 app, you're already getting all the new socket management goodies that MS has been working on.
如果您正在在ASP.NET Core 2.1应用程序中显式使用FlurlClient
,可以替代HttpClient
,并希望在利用以下优点的情况下将其注入您的类中: MS的HttpClientFactory
所提供的内容,我建议完全按照MS的规定在ConfigureServices
中设置HttpClientFactory
,并且当您需要FlurlClient
实例时,请使用带有HttpClient
实例的构造函数.例如,当使用类型化的客户机模式时,您的服务类可能如下所示:
If you are using FlurlClient
explicitly in an ASP.NET Core 2.1 app, as sort of a replacement for HttpClient
, and would like to inject it into your classes while taking advantage of what MS's HttpClientFactory
has to offer, I would suggest setting up HttpClientFactory
in ConfigureServices
exactly as prescribed by MS, and when you need a FlurlClient
instance, use the constructor that takes an HttpClient
instance. For example, when using the typed clients pattern, your service class might look like this:
public class MyService
{
private readonly IFlurlClient _flurlClient;
public MyService(HttpClient httpClient)
{
_flurlClient = new FlurlClient(httpClient);
}
}
这篇关于ASP.Net Core 2.1和IHttpClientFactory中的Flurl客户端生存期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!