Why use IHttpClientFactory instead of new HttpClient() in .NET

C# Language Interview Q&A November 13, 2026 csharp

new HttpClient() on every call: socket exhaustion (sockets stay in TIME_WAIT).

csharp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ======================================================================
// Q: Why IHttpClientFactory instead of new HttpClient()?
//
// - new HttpClient() on every call: socket exhaustion (sockets stay in
//   TIME_WAIT).
// - One static HttpClient forever: it does not see DNS changes.
// - IHttpClientFactory / typed clients: handler pooling and recycling, central
//   configuration (base address, headers), resilience (Q11), logging.
// ======================================================================

builder.Services.AddHttpClient<IErpClient, ErpClient>(c => c.BaseAddress = new(erpUrl))
                .AddStandardResilienceHandler();