IHttpClientFactory 单例 .NET 框架

IHttpClientFactory Singleton .NET Framework

场景

我正在尝试将现有的 HttpClient 更改为 IHttpClientFactory。当我验证现有代码时,它使用 using{...} 语句导致问题并被提及 here. So I thought of implementing singleton Http client and reached another blog related to this and it is here.

从所有这些中,我了解到最好的是 IHttpClientFactory 在 .NET Core 中引入。

实施计划

由于此应用程序在 ASP.NET MVC 4 中并且不使用 DI,因此我必须做一些没有 DI 框架的事情。根据我的搜索,从 Whosebug 得到了答案,并计划以同样的方式实现。同时,我还得到了另一个项目,它已经删除了所有依赖项,并且可以在不做所有事情的情况下在早期项目中使用。回购是 HttpClientFactoryLite.

问题

现在我可以通过初始化这个 class 来使用 HttpClientFactoryLite 了吗?描述中还提到它可以与现有的 DI 框架一起使用,以便 ClientFactory 可以注册为单例。请从自述文件中找到措辞

using HttpClientFactoryLite;

var httpClientFactory = new HttpClientFactory(); //bliss

If you are using dependency injection, make sure that IHttpClientFactory is registered as a singleton.

在我的场景中,我没有添加任何 DI 框架。所以我将在需要的地方初始化工厂。在这里我很困惑,有两件事

  1. HttpClientFactoryLite需要做单例class吗?

  2. 这个HttpClientFactoryclass怎么处理的?是否需要将其作为控制器的一部分或相同的 using 语句等处理?

  3. 根据的回答,Microsoft.Extensions.Http只提供HttpClientFactory,不提供新优化的HttpClient。这仅在 .NET Core 2.1 中可用。那么实现 IHttpClientFactory 有什么不同吗?

请指教

ASP.NET3.1:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddSingleton<IHttpClientFactory, HttpClientFactory>();
}

ASP.NET 将自动将正确的单例传递给需要在其构造函数中使用 IHttpClientFactory 的控制器。


没有DI-Container的穷人变体:

public static class Singleton<TInterface> 
{
    private static TInterface instance;
    public static TInterface Instance
    { 
        get => instance;
        private set => instance ??= value;
    }

    public static void Add<TConcrete>() where TConcrete : TInterface, new()
        => Instance = new TConcrete();

    public static void Add<TConcrete>(TConcrete instance) where TConcrete : TInterface
        => Instance = instance;

    // put dispose logic if necessary
}

用法:

// Application Entrypoint
Singleton<IHttpClientFactory>.Add<HttpClientFactory>();

// Class/Controller Property
private readonly IHttpClientFactory httpClientFactory 
    = Singleton<IHttpClientFactory>.Instance;