Is it better to have single instance of HttpClient for multiple calls?

What should the age of HttpClient for a WebAPI client? Is it better to have  single instance of HttpClient for multiple calls?Its really tricky . We will see that what is the life time of a Http client. In a single word let me tell you HttpClient has been designed to be re-used for multiple calls Not for one . Now I will explain How and Why.

Even across multiple topics. HttpClientHandler contains credentials and custom cookies for reuse over calls. Having a new HttpClient instance requires re-setting all of these things. Also, the DefaultRequestHeaders property contains custom properties for multiple calls. The need to reset these values ??on each request defeats the point.

HttpClient is meant for reuse, Another major benefit of HttpClient is the ability to add HttpMessageHandlers in the request / response pipeline to apply overall concerns. This can be for recording, checking, choking, forwarding, offline handling, and capturing metrics. All sorts of different things. If a new HttpClient is created on each request, all of these message handlers must be set up on each request, and any application-level status that is shared between the requests for those handlers must also be provided.

Whenever you use HttpClient features, you see that reusing an existing instance makes sense.

However, the biggest problem, in my opinion, is that when the HttpClient class is eliminated, it gets rid of HttpClientHandler, which forcibly closes the TCP / IP connection in the communications group managed by ServicePointManager. This means that each request with a new HttpClient requires the re-establishment of a new TCP / IP connection.

Leave a Reply

Your email address will not be published. Required fields are marked *