Using IHttpClientFactory AddHttpClient method to avoid Port Exhaustion


Using IHttpClientFactory AddHttpClient method to avoid Port Exhaustion

Using IHttpClientFactory in C# with AddHttpClient

In C# it’s incredibly simple to make an HTTP request, you need only to create an HttpClient, specify the URI and choose your method. But using the HttpClient recklessly can lead to a lot of trouble, but thankfully Microsoft covers a lot of that for us. All we need to do is to start using the IHttpClientFactory and its AddHttpClient method, and we already get rid of most of the problems.

Why do I need it?

You don’t actually need it, but it doesn’t hurt at all to use it, and it is extremely easy to do it. Quoting Microsoft, some of the benefits are:

  • Prevents port exhaustion
  • Provides a centralized way of configuring multiple HttpClients with different behaviors
  • Enables the use of Polly in order to increase resiliency

Show me the code

There are many ways to implement this feature, but we will go with the simplest. First of all, you will need both Microsoft.Extensions.Http and Microsoft.Extensions.DependencyInjection added to your project. Then, we need to add it to our services.

using Microsoft.Extensions.DependencyInjection;

var serviceCollection = new ServiceCollection();

serviceCollection.AddHttpClient();

Yep. That’s it. Just by using AddHttpClient, we now can get an HttpClient wherever we want. Let’s create a class called Requester which will simply send a GET request to Google, and call it in our main method.

class Requester
{
    public HttpClient HttpClient { get; }

    public Requester(HttpClient httpClient)
    {
        HttpClient = httpClient;
    }

    public async Task DoRequestAsync() 
        => await HttpClient.GetAsync("https://www.google.com/");
}

Our Program.cs should be looking like this now:

using Microsoft.Extensions.DependencyInjection;

var serviceCollection = new ServiceCollection();

serviceCollection.AddHttpClient();
serviceCollection.AddScoped<Requester>();

var provider = serviceCollection.BuildServiceProvider();

var requester = provider.GetRequiredService<Requester>();
await requester.DoRequestAsync();

As mentioned before, this is the simplest possible approach, which will already greatly benefit your application. More complex setups can be achieved as described in this article, which you can follow to tailor your HttpClient instances to your needs.