In .NET applications, HttpClient is very well known class, and it is used for making HTTP requests from C# code. In this article, we will have a look HttpClient class and a middleware that can be used to get HttpClient instances for HTTP communication from C# code.
As stated earlier, HttpClient class can be used to make HTTP requests and receive HTTP responses. Each instance of HttpClient acts as session for HTTP communication.
Each instance of HttpClient is a collection of settings applied to all requests executed by that instance. Every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances.
This class is recommended to be instantiated once in the application and it should be reused throughout the life of application.
If HttpClient class is instantiated for every requested, then it will exhaust the number of sockets available. This might result in deterioration of application performance (due to slower HTTP responses) and eventually application would start throwing SocketException errors.
So, this background is enough to proceed our discussion to the new middleware.
.NET provides a factory IHttpClientFactory, which can be used to create instances of HttpClient. This factory provides a central location for creating HttpClient instances and it also provides ability to configure logging experience for the HTTP communication.
One important facility provided by factory is, it provides a central location for configuring logical HttpClient instances.
So, let’s say the application needs to access APIs from two different sources, GitHub and Google maps APIs. The factory can be used to get one HttpClient instance for all GitHub API calls and the other HttpClient instance to make Google maps API calls.
This factory can be configured for an application via middleware.
Consuming the IHttpClientFactory is three step process:
- First step, use
AddHttpClientmiddleware to register the factory
- Second step, IHttpClientFactory can be injected in a class
- Third step, is to use CreateClient method to get HttpClient instance
Below sample code shows how to use this middleware. Note that every time a CreateClient method is called, it creates a new instance of HttpClient. Hence the caller of this method does have responsibility to cache the HttpClient instance (not shown in below demo).
This was basic usage scenario. In coming articles, we will see how to use named instances and typed instances of HttpClient using this middleware. Do you have any specific questions/suggestions ? Let me know your thoughts.