ASP.NET Core中HttpClientFactory的连接存活、复用及池化特性问询
Let's break these down clearly—this is such a common point of confusion when working with .NET Framework vs. ASP.NET Core, so great questions!
1. Does HttpClientFactory in ASP.NET Core keep connections alive after requests complete, like HttpClient in .NET Framework?
Absolutely. Both rely on underlying connection pooling to maintain alive connections via HTTP Keep-Alive (the default behavior for both).
In .NET Framework, HttpClient uses ServicePointManager to manage connection pools. ASP.NET Core's HttpClientFactory uses the modern SocketsHttpHandler, which also maintains a connection pool. The core difference isn't whether connections stay alive, but how the client/handler lifecycle is managed to avoid pitfalls like stale DNS caching or accidental connection leaks that plagued long-lived HttpClient instances in .NET Framework.
2. Is HttpClientFactory like an HttpClient pool? Do clients stay alive after requests, and does it reuse or create new clients per request?
Let's clarify the mechanics here, since this is where most people mix things up:
- It’s an
HttpMessageHandlerpool, not anHttpClientpool: Every time you callCreateClient()from the factory, you get a new, lightweightHttpClientinstance. But this new client reuses a pooledHttpMessageHandler(which has a default lifetime of 2 minutes). - Connections stay alive: The pooled
HttpMessageHandlermanages the actual HTTP connections. After a request completes, the connection stays in the handler's pool (following Keep-Alive rules) for reuse in future requests. - Why this design works: Creating a new
HttpClienteach time is cheap (they're just thin wrappers around the handler), and the pooled handler avoids the overhead of spinning up new connections constantly. It also fixes the old .NET Framework issue where long-livedHttpClientinstances would cache DNS entries indefinitely—since handlers are recycled after 2 minutes, DNS refreshes work as expected.
内容的提问来源于stack exchange,提问作者Tech

