.NET Core5 中 HttpClient 和 IHttpClientFactory 实例的区别

Difference between instance of HttpClient and IHttpClientFactory in .NET Core5

下面是我的Startup.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient();
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

和控制器:

[ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
        private readonly HttpClient _httpClient;
        private readonly IHttpClientFactory _httpClientFactory;
        public TestController(HttpClient httpClient, IHttpClientFactory httpClientFactory)
        {
            _httpClient = httpClient;
            _httpClientFactory = httpClientFactory;
        }

        [HttpGet]
        [Route("getdata")]
        public async Task GetData()
        {
            var baseAddress = "http://youtube.com";

            var response = await _httpClient.GetAsync(baseAddress);

            var client = _httpClientFactory.CreateClient();
            response = await client.GetAsync(baseAddress);
        }
    }

如您所见,我可以通过两种方式获取 HttpClient 的实例:

  1. 通过注入 HttpClient
  2. 通过注入 IHttpClientFactory 然后 _httpClientFactory.CreateClient();

虽然我使用这两个实例都得到了响应,但我的问题是它们之间有什么区别?什么时候使用哪一个?

如果您只是 post 信号 request.there 注入 httpclient 实例和使用 httpclientfactory 创建 httpclient 实例之间甚至没有区别。

如果您使用多个 httpclient 实例或将 httpclient 重复用于 post 多个请求,可能会出现一些问题,使用 httpclient 可以解决这些问题。

您可以创建具有不同设置的 httpclients,如下所示:

在startup.cs中:

services.AddHttpClient("client_1", config =>  
            {
                config.BaseAddress = new Uri("http://client_1.com");
                config.DefaultRequestHeaders.Add("header_1", "header_1");
            });
services.AddHttpClient("client_2", config =>
            {
                config.BaseAddress = new Uri("http://client_2.com");
                config.DefaultRequestHeaders.Add("header_2", "header_2");
            }); 

在你的控制器中:

var client1 = _httpClientFactory.CreateClient("client_1");
var client2 = _httpClientFactory.CreateClient("client_2");