Correct Way To Use HTTP Client in Azure Functions
    • Dark
      Light
    • PDF

    Correct Way To Use HTTP Client in Azure Functions

    • Dark
      Light
    • PDF

    Article Summary

    #ServerlessTips - Azure Functions
    Author: Mandar Dharmadhikiri Business & Integration Architecture Manager

    .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

    download 241

    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.

    download 251

    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

    download 261

    download 34

    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.

    MicrosoftTeams-image 503


    Was this article helpful?