.NET Core 2.1 – Use HttpClientFactory to implement resilient HTTP requests

The original and well-know HttpClient class can be easily used, but in some cases, it is not being properly used by many developers.

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’.

Therefore, HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. That issue will result in SocketException errors. Possible approaches to solve that problem are based on the creation of the HttpClient object as singleton or static.

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.

To address those mentioned issues and make the management of HttpClient instances easier, .NET Core 2.1 offers a new HttpClientFactory that can also be used to implement resilient HTTP calls by integrating Polly with it.

Read more…

I hope this will help !!!!