Using IHttpClientFactory in .NET Core 3.1

Goal

Use IHttpClientFactory to create HTTP clients with proper lifecycle management and avoid socket exhaustion.

Register the factory

//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();
}

Inject and use

//HealthController.cs
private readonly IHttpClientFactory _clientFactory;

public HealthController(IHttpClientFactory clientFactory)
{
    _clientFactory = clientFactory;
}

// Create clients on demand
var client = _clientFactory.CreateClient();
var response = await client.GetAsync("https://api.example.com/health");