What is the overhead of creating a new HttpClient per call in a WebAPI client?

前端 未结 7 1939
心在旅途
心在旅途 2020-11-22 07:26

What should be the HttpClient lifetime of a WebAPI client?
Is it better to have one instance of the HttpClient for multiple calls?

Wh

7条回答
  •  误落风尘
    2020-11-22 07:41

    As a first issue, while this class is disposable, using it with the using statement is not the best choice because even when you dispose HttpClient object, the underlying socket is not immediately released and can cause a serious issue named ‘sockets exhaustion.

    But there’s a second issue with HttpClient that you can have when you use it as singleton or static object. In this case, a singleton or static HttpClient doesn't respect DNS changes.

    in .net core you can do the same with HttpClientFactory something like this:

    public interface IBuyService
    {
        Task GetBuyItems();
    }
    public class BuyService: IBuyService
    {
        private readonly HttpClient _httpClient;
    
        public BuyService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
    
        public async Task GetBuyItems()
        {
            var uri = "Uri";
    
            var responseString = await _httpClient.GetStringAsync(uri);
    
            var buy = JsonConvert.DeserializeObject(responseString);
            return buy;
        }
    }
    

    ConfigureServices

    services.AddHttpClient(client =>
    {
         client.BaseAddress = new Uri(Configuration["BaseUrl"]);
    });
    

    documentation and example at here

提交回复
热议问题