zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用 .NET 4.6.2 中的 HttpClientFactory(Use HttpClientFactory from .NET 4.6.2)

Net from use 4.6 使用
2023-09-11 14:15:05 时间

有一个 .NET 4.6.2 控制台应用程序(使用 Simple Injector)。我需要调用 HTTP 服务。直接使用 HttpClient 遇到问题后,我尝试改用 HttpClientFactory (https://github.com/aspnet/HttpClientFactory)。

项目/库是 .NET Standard 2.0 所以应该吗?在 .NET 4.6.2 中工作,但它使用 IServiceCollection 之类的东西,它只在 Core 中。

所以我的问题是我可以在非核心应用程序中使用 HttpClientFactory。

 

您需要添加 Microsoft.Extensions.Http 和 Microsoft.Extensions.DependencyInjection。这是我的ConsoleApp代码,大家可以参考一下

class Program
{
     static void Main(string[] args)
     {
         Test();
         Console.Read();
     }
     static async void Test()
     {
        var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
        var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
        var client = httpClientFactory.CreateClient();
        var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://www.baidu.com"));
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(content);
     }
}

  

【问题】:

  • 如果循环 Test(),它会创建多个客户端实例
  • 是的,但是如果您在此方法之外注册 serviceProvider,那么每个 var client = httpClientFactory.CreateClient(); 都会返回相同的客户端
  • HttpClient 可以创建多次也没关系。 HttpMessageHandler 会被复用,只要你使用同一个工厂实例,这是这里的重要部分。
  •  

改:

class Program
{

    static IHttpClientFactory httpClientFactory ;
    
     static void Main(string[] args)
     {
        var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
     httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
         Test();
         Console.Read();
     }
     static async void Test()
     {
        var client = httpClientFactory.CreateClient();
        var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://www.baidu.com"));
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(content);
     }
}