在控制檯程序中使用IHttpClientFactory

一、前言

一般來說我們發送Web請求的時候,都是通過HttpClient。但是使用的時候會有兩個問題:

  1. 因爲HttpClient實現了IDisposable接口,每次使用如果都new一個對象的話,最後會耗盡你的主機端口。微軟建議使用單例模式。
  2. 如果使用單例模式的話,端口是節省了,但是請求地址的DNS如果改變了的話,這個單例並不知道。

爲了解決上面的兩個問題,社區就出現了HttpClientFactory的開源方案。現在微軟也將其添加到了. net core中。並且基於. net standard 2.0。

如果是在.Net Core的web項目中,我們可以直接在ConfigureServices方法中配置使用

services.AddHttpClient();

那麼在控制檯項目中如何使用呢。在.net framework和.net core的控制檯中都可以使用, 但是要求你的 .net framework版本至少爲4.6.1.

二、示例代碼

添加一個控制檯項目,並nuget上安裝下面兩個包:Microsoft.Extensions.Http和Microsoft.Extensions.DependencyInjection。

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;

namespace HttpClientFactoryTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Test();
            Console.ReadKey();
        }

        static async void Test()
        {
            var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
            var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
            var client = httpClientFactory.CreateClient();
            var response = await client.GetAsync("http://www.baidu.com");
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }
}

運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章