Flurl client lifetime in ASP.Net Core 2.1 and IHttpClientFactory

半城伤御伤魂 提交于 2019-12-04 03:53:18

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 FlurlClients into controllers or service classes, and are instead using Flurl like this:

await url.GetJsonAsync();

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.

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);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!