skip to content

Named & Typed Clients

AddHttpClient registers named and typed clients whose handlers are pooled and rotated, avoiding socket exhaustion and stale DNS. Interviewers probe handler lifetime and typed clients in singletons.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core, why should outgoing HTTP calls go through IHttpClientFactory and AddHttpClient rather than a new HttpClient per call or one static instance?

level: juniorimportance: must knowfreq 80%

answer

  1. the handler owns the connections
  2. new-and-dispose per call: no reuse
  3. one static client: stale DNS
  4. HandlerLifetime defaults to 2 minutes
  5. CreateClient uses disposeHandler: false

basics

~20 s

An HttpClient's handler owns its connection pool. A new client per call discards connections and can exhaust sockets; one static client can miss DNS changes. IHttpClientFactory pools handlers per name and rotates them every two minutes by default.

solid answer

~40 s

The expensive object is not `HttpClient` but its `HttpMessageHandler`, which owns the open connections. `using var client = new HttpClient()` per call builds and tears down a handler each time, so nothing is reused and closed sockets pile up until the machine runs out of ports under load. A single static client fixes reuse but puts no age limit on its connections, so a busy client can miss a DNS change behind the downstream host. `builder.Services.AddHttpClient()` registers a singleton `IHttpClientFactory` that keeps one handler chain per client name and replaces it after `HandlerLifetime` (two minutes by default). `CreateClient(name)` returns a cheap new `HttpClient` wrapped around the pooled handler with `disposeHandler: false`, so disposing it is harmless. On top of that you get central configuration per name, typed clients, `DelegatingHandler` pipelines and built-in logging.

code

csharp · 16 lines
csharp
// Program.cs
builder.Services.AddHttpClient("rates", client =>
{
    client.BaseAddress = new Uri("https://rates.example.com/");
    client.Timeout = TimeSpan.FromSeconds(15);
});

// A Minimal API endpoint in the web shop
app.MapGet("/checkout/shipping/{zip}", async (string zip, IHttpClientFactory factory, CancellationToken ct) =>
{
    HttpClient client = factory.CreateClient("rates"); // new client, pooled handler
    var quote = await client.GetFromJsonAsync<RateQuote>($"v2/quotes?zip={zip}", ct);
    return Results.Ok(quote);
});

record RateQuote(decimal Amount, string Currency);

go deeper

for a junior

Recall that the handler, not HttpClient, owns connections, that per-call creation exhausts sockets, and that AddHttpClient plus IHttpClientFactory is the fix.

for a middle

Explain handler pooling per client name, the two-minute HandlerLifetime, why CreateClient returns a new client with disposeHandler false, and what the static-client alternative needs.

for a senior

Show you can spot pinned handlers in long-lived objects and know that since .NET 9 the default SocketsHttpHandler recycles connections on the HandlerLifetime schedule.

for a principal

Weigh a long-lived client with PooledConnectionLifetime against the factory for non-web hosts and shared libraries, and set a team convention for outgoing calls.

## The object that actually costs something An `HttpClient` is a thin front end. The work happens in its **message handler** chain, and at the bottom of that chain sits a **primary handler** (on .NET 10, a `SocketsHttpHandler`) that owns the pool of open TCP and TLS connections to each server. Two ways of managing that handler by hand both go wrong: | Pattern | What happens | Symptom in production | |---|---|---| | `new HttpClient()` per call, then `Dispose` | each call builds a fresh handler and pool, then closes it | no connection reuse, extra handshakes, sockets left in the OS's closing states; under load the process runs out of ports | | one `static readonly HttpClient` for the app | the pool lives as long as the process | busy connections are never re-opened, so the client can keep talking to the old IP after a DNS change | The second pattern is fine *if* the primary handler is told to recycle connections (`SocketsHttpHandler.PooledConnectionLifetime`), which is exactly the job the factory takes on for you. ## What IHttpClientFactory does `builder.Services.AddHttpClient()` (and every overload that takes a name or a type) registers the factory machinery from `Microsoft.Extensions.Http`, which ships with ASP.NET Core: - **`IHttpClientFactory` is a singleton.** It keeps, per **logical client name**, one active handler chain built from that name's configuration. - **`HttpClientFactoryOptions.HandlerLifetime` defaults to two minutes.** After it expires the next `CreateClient` call gets a newly built chain; the old one moves to an expired list and is disposed only once nothing references it any more. The minimum accepted value is one second; `Timeout.InfiniteTimeSpan` turns rotation off. - **`CreateClient(name)` always returns a new `HttpClient`**, constructed over the pooled handler with `disposeHandler: false`. Creating it is cheap, and disposing it does not close the pooled connections. - **Since .NET 9 the default primary handler is `SocketsHttpHandler`** with `PooledConnectionLifetime` preset to the client's `HandlerLifetime`, so connections recycle even inside a handler that lives longer than planned. - **Configuration is centralised.** Base address, default headers, `Timeout`, extra `DelegatingHandler`s and the primary handler are declared once per name in `Program.cs` instead of at every call site. - **Logging comes for free.** The factory adds logging handlers to every chain, so each outgoing request and its duration are logged under categories that start with `System.Net.Http.HttpClient.<name>` (`.LogicalHandler` outside your handlers, `.ClientHandler` next to the wire). ## Using it The usual shapes, from least to most structured: 1. **Basic**: inject `IHttpClientFactory` and call `CreateClient()` with no name; you get the default configuration. 2. **Named**: `AddHttpClient("rates", c => c.BaseAddress = ...)`, then `CreateClient("rates")`. 3. **Typed**: `AddHttpClient<ShippingRatesClient>(...)`; the factory constructs `ShippingRatesClient` with a configured `HttpClient` injected into its constructor. In a web shop that prices delivery through a shipping-rates provider, the typed form keeps the provider's base address, headers and parsing in one class that controllers and Minimal API handlers simply inject. ## Common misreadings - **"HttpClient must never be disposed."** A client from the factory may be disposed or not; the factory tracks the handler either way. The real rule is not to create *handlers* per call. - **"The factory caches HttpClient instances."** It caches handlers. Every `CreateClient` call is a new `HttpClient`, so mutating one client's `DefaultRequestHeaders` does not leak into the next. - **"HandlerLifetime is a request timeout."** It controls how long a handler chain is reused. How long one request may take is `HttpClient.Timeout`, 100 seconds unless configured. - **"With the factory, keeping a client forever is fine."** A client held in a singleton pins one handler chain; the factory cannot rotate it. Since .NET 9 the connection lifetime still recycles connections, but the handlers and their dependencies stay frozen. ## What the factory does not do for you The factory manages *where handlers come from and how long they live*. Several things stay your job: - **Retries, circuit breaking and per-attempt timeouts** are not built in; they come from the resilience handlers you add to a client's builder. - **Cancellation** still has to be passed in: give `GetFromJsonAsync` or `SendAsync` the request's `CancellationToken` so a call stops when the shopper leaves. - **Error handling** is unchanged: a non-success status from `GetFromJsonAsync` still throws `HttpRequestException`, and `HttpClient.Timeout` still applies. - **Lifetime discipline** for the clients you hold: a client the factory created is only rotated if you let it go and ask for a new one. In short, the factory removes the two classic lifetime bugs and gives you one place to configure each downstream API; it does not make a remote call reliable on its own. ## When a static client is still reasonable Outside DI, for instance in a small console tool, the documented alternative is a long-lived `HttpClient` over a `SocketsHttpHandler` whose `PooledConnectionLifetime` is set (for example to two minutes). That solves both port exhaustion and stale DNS without the factory. Inside an ASP.NET Core app, the factory is the default answer because it adds configuration, handler pipelines, logging and typed clients on top of the same connection management.

  • Should you wrap a client from IHttpClientFactory.CreateClient in a using block?
    You may, and it does no harm: the factory builds the client with `disposeHandler: false`, so disposing it leaves the pooled handler and its connections intact. The documentation says disposing is generally not necessary because the factory tracks and disposes the handler resources itself. What you must not do is create your own handler per call.
  • What happens to in-flight requests when a handler's two-minute HandlerLifetime expires?
    Nothing abrupt. Expiry only means the next `CreateClient` call gets a newly built chain. The old chain moves to an expired list that a cleanup timer checks periodically, and it is disposed only once no `HttpClient` references it, so requests already using it finish normally.

A taxi firm keeps a fleet of cars and swaps each car out every couple of months; customers book a ride (a new HttpClient) rather than buying a car per trip or driving one car until it falls apart.

  • Says a new HttpClient per request is fine as long as it is disposed
  • Believes IHttpClientFactory caches and hands back the same HttpClient instance
  • Thinks HandlerLifetime is how long a single request may take
  • Claims one static HttpClient has no downside at all
  • Believes disposing a factory-created client closes the pooled connections

Assumes ASP.NET Core 10 on .NET 10; since .NET 9 the factory's default primary handler is SocketsHttpHandler with PooledConnectionLifetime set to HandlerLifetime.

open as a page

In ASP.NET Core, how does a named HttpClient registered with AddHttpClient differ from a typed client, and when would you choose each?

level: middleimportance: must knowfreq 66%

basics

~20 s

A named client is configuration stored under a string and fetched with IHttpClientFactory.CreateClient(name). A typed client is a class whose constructor receives a configured HttpClient; DI injects the class itself, registered transient. Typed clients suit one downstream API wrapped in methods.

open as a page

In ASP.NET Core, how does a DelegatingHandler add an auth header to a typed HttpClient's requests, and which DI scope does it live in?

level: middleimportance: should knowfreq 52%

basics

~20 s

Derive from DelegatingHandler, set the header in SendAsync and call base.SendAsync; register it transient and chain AddHttpMessageHandler<T>() on the client. The factory resolves it from its own handler scope, which lives as long as the handler chain, not the incoming request.

open as a page

In an ASP.NET Core typed client, what do GetFromJsonAsync and HttpClient.Timeout do when the downstream API answers 404 or answers too slowly?

level: middleimportance: should knowfreq 44%

basics

~10 s

GetFromJsonAsync checks the status and throws HttpRequestException, with StatusCode set, on a 404. If no answer arrives within HttpClient.Timeout, 100 seconds by default, the call throws TaskCanceledException whose inner exception is a TimeoutException.

open as a page

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?

level: seniorimportance: should knowfreq 48%

basics

~20 s

The 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.

open as a page