Correct Way To Use HTTP Client in Azure Functions
.Net core provides HttpClient to make HTTP calls. The HttpClient internally implements the IDisposable interface. So, a call to a REST API can be made as below
Above code creates an instance of the HttpClient every time the function is invoked. The using statement disposes of the HttpClient but the internal socket connection is not released immediately. and the code can run into socket exhaustion problem.
To avoid this, you can create a static instance of HttpClient as shown below.
This also is not perfect as the static instance of the HttpClient will not respect the DNS changes in the remote API.
The correct and the recommended way to implement the HttpClient is using IHttpClientFactory. The HttpClient can now be registered in the startup and can be requested using DI as shown below
The IHttpClientFactory maintains a pool of timed HttpMessageHandlers. Each time a HttpClient handler is requested, the factory creates a new instance but uses the HttpMessageHandler from the pool thus better managing socket connections. The HttpMessageHandlers are transient and post expiry of their lifetime, new handlers are added to the pool thus providing a chance to respect the remote API DNS changes.
The implementation can be made more resilient.