In an ASP.NET Core 10 app, a singleton service takes a typed HttpClient in its constructor; what goes wrong, and how do HandlerLifetime and PooledConnectionLifetime change the answer?
answer
- transient captured for good
- the factory can no longer rotate
- SocketsHttpHandler default since .NET 9
- PooledConnectionLifetime preset to HandlerLifetime
- inject IHttpClientFactory instead
basics
~20 sThe transient typed client is captured for the app's lifetime, so its handler chain is never rotated. Since .NET 9 the default SocketsHttpHandler still recycles connections every HandlerLifetime, but custom primary handlers, delegating handlers and their scoped dependencies stay frozen.
solid answer
~50 sA typed client is registered transient, but a singleton resolves it once, so one `HttpClient` and its handler chain live as long as the app and `IHttpClientFactory` can no longer swap it when `HandlerLifetime` (two minutes) expires. Before .NET 9 the default `HttpClientHandler` put no age limit on connections, so a busy captured client could miss DNS changes indefinitely. Since .NET 9 the factory's default primary handler is a `SocketsHttpHandler` whose `PooledConnectionLifetime` is preset to the `HandlerLifetime`, so connections still recycle and DNS is re-read. What stays frozen: a primary handler you configured yourself with `ConfigurePrimaryHttpMessageHandler`, every `DelegatingHandler`, and the services in the handler's DI scope. The fixes are to inject `IHttpClientFactory` and call `CreateClient` per operation, to make the consumer scoped or transient, or, if a long-lived client is intended, to set `PooledConnectionLifetime` explicitly via `UseSocketsHttpHandler` and disable rotation with `SetHandlerLifetime(Timeout.InfiniteTimeSpan)`.
code
csharp · 13 lines// Captures one handler chain for the life of the app
public sealed class RatesWarmup(RatesClient rates) { /* ... */ }
builder.Services.AddSingleton<RatesWarmup>();
// Fix: create a client per run from the factory
public sealed class RatesWarmupFixed(IHttpClientFactory factory)
{
public async Task RunAsync(CancellationToken ct)
{
HttpClient http = factory.CreateClient("rates");
await http.GetAsync("v2/health", ct);
}
}go deeper
Recall that typed clients are transient and must not be stored in a singleton, and that IHttpClientFactory is the safe thing to inject there.
Explain how HandlerLifetime rotation only helps newly created clients and how PooledConnectionLifetime recycles connections inside one handler.
Diagnose a captured client on .NET 10: check for a custom primary handler, frozen delegating handlers and handler-scope services, then pick the right fix.
Set guidance for long-running consumers such as hosted services and caches, and decide when a deliberately long-lived client with an explicit connection lifetime is the cleaner design.
## How the capture happens `AddHttpClient<RatesClient>()` registers `RatesClient` as a **transient** service; each resolution asks the factory for a fresh `HttpClient` over the currently active handler chain. A **singleton** that takes `RatesClient` in its constructor resolves it exactly once, at first use, and holds it for the life of the process. The factory's rotation works by handing *new* clients a *new* chain after `HandlerLifetime`; it cannot reach into an object someone is already holding. So the singleton keeps the very first chain forever. The DI container does not warn about this. Scope validation only rejects **scoped** services resolved from the root provider; a transient captured by a singleton is legal, which is why the bug tends to surface only as odd network behaviour weeks later. ## What used to break, and what .NET 9 changed | Piece of the chain | Before .NET 9 | .NET 9 and later (default primary handler) | |---|---|---| | Primary handler | `HttpClientHandler`, no age limit on a busy connection | `SocketsHttpHandler` with `PooledConnectionLifetime` = `HandlerLifetime` | | DNS changes behind the host | missed while connections stay busy | picked up as connections are recycled | | Your `DelegatingHandler` instances | frozen | still frozen | | Services in the handler's DI scope | frozen | still frozen | | A primary handler you configured | frozen | still frozen, unless you set its lifetime | The .NET 9 change was made precisely because typed and named clients were so often captured. It is a mitigation at the connection level, not a return of rotation. ## What still goes wrong on .NET 10 - **Custom primary handlers.** `ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ... })` replaces the default, and the preset `PooledConnectionLifetime` goes with it. Long-held clients are back to stale connections. - **Frozen delegating handlers.** An auth handler that read a token or configuration in its constructor keeps that value for as long as the singleton lives. - **Frozen handler scope.** The DI scope the factory created for the chain is never disposed, along with whatever scoped services it holds. - **Configuration changes ignored.** Named-options changes take effect only for clients and chains the factory creates *later*, which the singleton never receives. ## Fixes, in order of preference 1. **Do not capture.** Make the consumer scoped or transient, so each request resolves a fresh typed client. 2. **Create per operation.** If the consumer must be a singleton (a cache warmer, a hosted service), inject `IHttpClientFactory` and call `CreateClient("rates")` each time it does work; each call sees the current chain. 3. **Own the lifetime deliberately.** When a long-lived client is the design, configure the primary handler yourself and give it a connection lifetime: - `.UseSocketsHttpHandler((h, _) => h.PooledConnectionLifetime = TimeSpan.FromMinutes(2))` - `.SetHandlerLifetime(Timeout.InfiniteTimeSpan)` so the factory stops pretending to rotate. Delegating handlers then must not cache anything that expires. ## Spotting it in a running system Captured clients rarely fail loudly. The signals are indirect: - on a client with its own primary handler (or on .NET 8), one instance keeps calling the old address after a DNS failover while freshly started instances are fine; - an auth handler starts receiving 401 responses hours after startup because it read a token once in its constructor; - a configuration change to the client's base address or headers reaches new instances but never the long-running one. To find the culprit, look at every singleton, every `IHostedService` or `BackgroundService`, and every keyed `HttpClient` registered with a singleton lifetime, and check whether its constructor takes a typed client or an `HttpClient`. A typed client parameter on any of them is the first suspect. ## Two lifetimes, two layers - **`HandlerLifetime`** (factory level, default two minutes, minimum one second): how long the factory hands out the same handler chain before building a new one. It only helps clients created *after* expiry. - **`PooledConnectionLifetime`** (connection level, on `SocketsHttpHandler`): how long one TCP connection may be reused before it is closed after its current request. It works inside a single long-lived handler. The same reasoning applies to `AddAsKeyed(ServiceLifetime.Singleton)` and to a keyed transient `HttpClient` injected into a singleton; the API documentation warns that such clients cannot take part in handler rotation.
- Why does ValidateScopes in Development not catch a typed client injected into a singleton?Scope validation only rejects a scoped service resolved from the root provider, directly or through a singleton. A typed client is transient, and capturing a transient in a singleton is legal, so nothing fails at startup.
- After moving to .NET 10, a team's captured client still ignores a DNS failover. What would you check first?Whether the client configures its own primary handler, for example `ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { ... })`. That replaces the default `SocketsHttpHandler` and its preset `PooledConnectionLifetime`, so long-held connections are never recycled. Either stop capturing the client or switch to `UseSocketsHttpHandler` and set `PooledConnectionLifetime`.
- Says capturing a typed client is harmless because IHttpClientFactory is a singleton
- Believes the factory rotates handlers inside clients that are already held
- Thinks .NET 9 also refreshes captured DelegatingHandlers and their dependencies
- Treats HandlerLifetime and PooledConnectionLifetime as the same setting
- Expects ValidateScopes to flag a transient captured by a singleton
Assumes ASP.NET Core 10 on .NET 10; since .NET 9 the factory's default primary handler is SocketsHttpHandler with PooledConnectionLifetime preset to HandlerLifetime, which earlier releases lacked.