الانتقال إلى المحتوى
.NETASP.NET Core· 7 دقائق للقراءة

new HttpClient() in a using Block Is a Bug: IHttpClientFactory Explained

Each HttpClient owns a connection pool, so disposing one per call leaves a socket behind every time, while one that lives forever never sees DNS changes. What IHttpClientFactory pools, rotates and leaves to you.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A checkout service calls a payment provider. Code review approved it without comments: the HttpClient is created in a using declaration, exactly as you'd treat any disposable. It passes every test. On the first real traffic peak, calls to the provider start failing with socket errors, and netstat on the server lists thousands of connections to the provider in the TIME_WAIT state. A colleague's quick fix, one static client for the whole app, stops the errors. A month later the provider moves to new IP addresses, and the service keeps calling the old ones until it's restarted.

The common misconception

The belief: HttpClient implements IDisposable, so the correct, careful thing is to create one per request and dispose it when the request is done.

That's the rule for almost everything else in .NET. Files, streams, database connections: if it's disposable, wrap it in using, and analyzers will remind you when you don't. HttpClient also looks like a lightweight request object, with a base address, a few headers and a GetAsync method. And the per-call version works perfectly in development and at low traffic, so nothing contradicts the rule until production does.

The rule assumes that disposing an object only cleans up after it. For HttpClient, disposing also throws away something expensive that was meant to be reused.

What actually happens

An HttpClient is a front for a connection pool

Each HttpClient has a handler, SocketsHttpHandler in .NET, and the handler owns a pool of open connections. Requests to the same server reuse a pooled connection, so the TCP and TLS handshakes happen once. When the client owns its handler, disposing the client disposes the handler and closes its connections. A new client per request means a new pool per request: a fresh connection, a fresh handshake, and a close, every time.

A closed connection keeps its port for a while

TCP doesn't release a port the moment a connection closes. The side that closes it keeps the port in the TIME-WAIT state for a period defined by the protocol. In a test on .NET 10, 1,000 sequential requests with using var client = new HttpClient() left 1,000 sockets in TIME_WAIT. The same 1,000 requests through one shared client, or through IHttpClientFactory, left none, and used a single connection. At a high request rate, that leftover state is what leads to .

A client that lives forever never looks up DNS again

HttpClient resolves a host name only when it opens a connection, and it ignores the DNS record's time to live. A pooled connection can stay open indefinitely, so a static client keeps talking to the IP it resolved at startup. That's the second half of the hook: the static client fixed the ports and broke failover. The fix is SocketsHttpHandler.PooledConnectionLifetime, which closes connections after a set time so the next one resolves the name again.

What IHttpClientFactory pools and rotates

AddHttpClient registers IHttpClientFactory. The factory keeps one handler per client name, and every HttpClient it hands out wraps the pooled handler. Disposing such a client doesn't dispose the handler, so it doesn't close connections. Handlers are recycled after their lifetime, two minutes by default, so new connections pick up DNS changes. The catch: the factory controls only the clients it hasn't handed out yet. Its clients are meant to be short-lived, and a client kept for hours keeps its old handler.

The payment call, fixed

Both versions post a ChargeRequest and read a PaymentResult:

C# PaymentGateway.cs
public sealed class PaymentGateway{    public async Task<PaymentResult?> ChargeAsync(ChargeRequest request)    {        // A new connection pool per call: a new TCP and TLS handshake,        // and one more socket left in TIME_WAIT after disposal        using var http = new HttpClient        {            BaseAddress = new Uri("https://payments.example.com")        };        var response = await http.PostAsJsonAsync("/charges", request);        response.EnsureSuccessStatusCode();        return await response.Content.ReadFromJsonAsync<PaymentResult>();    }}

Outside dependency injection, in a library or a console tool, the documented alternative is one long-lived client whose connections expire:

C# Http.cs
static class Http{    // Connections are replaced every 2 minutes, so DNS changes are picked up    public static readonly HttpClient Shared = new(new SocketsHttpHandler    {        PooledConnectionLifetime = TimeSpan.FromMinutes(2)    });}

Five ways to hold an HttpClient

PatternReuses connectionsSees DNS changesUse it for
new HttpClient() per callNo, and leaves a port in TIME_WAITYes, at a high costNothing in server code
One static client, default handlerYesNo, connections can live indefinitelyNothing, without a connection lifetime
static client with PooledConnectionLifetimeYesYes, as connections are replacedLibraries and apps without DI
IHttpClientFactory, named or typedYes, through pooled handlersYes, handlers rotate every 2 minutes by defaultASP.NET Core apps
Typed client captured by a singletonYesNo, the factory no longer controls itNothing; inject the factory instead

How to apply it in your project

  1. Search for new HttpClientFind every new HttpClient( in server code. Each one inside a method, a constructor of a short-lived service, or a using is a candidate for a typed or named client.
  2. Register clients where the app startsMove base addresses, default headers and timeouts into AddHttpClient calls in Program.cs, one typed client per external API, so the configuration lives in one place.
  3. Check who holds the clientsLook for typed clients injected into singletons, background services and middleware constructors. Switch those to IHttpClientFactory.CreateClient per operation, or to a handler with PooledConnectionLifetime.
  4. Watch the sockets under loadDuring a load test, count connections in TIME_WAIT to each downstream host. A number that grows with the request count means something is still creating its own handlers.

Key takeaways

  • An HttpClient fronts a connection pool; disposing it per call throws the pool away and leaves a port in TIME_WAIT each time.
  • A client that lives forever reuses connections indefinitely and never re-resolves DNS unless PooledConnectionLifetime is set.
  • IHttpClientFactory pools handlers and rotates them every two minutes by default; its clients are cheap, short-lived and safe to dispose.
  • Typed clients are transient: don't capture them in singletons, or you're back to a client that never sees DNS changes.

📚 المصادر

  1. HttpClient guidelines for .NET — Microsoft Learn
  2. Use the IHttpClientFactory — Microsoft Learn
  3. Make HTTP requests using IHttpClientFactory in ASP.NET Core — Microsoft Learn

التعليقات (0)