In ASP.NET Core, how does a named HttpClient registered with AddHttpClient differ from a typed client, and when would you choose each?
answer
- a string name vs a class
- CreateClient("name") on the factory
- constructor takes an HttpClient
- typed clients are transient
- AddAsKeyed, scoped by default
basics
~20 sA 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.
solid answer
~40 s`AddHttpClient("rates", c => ...)` stores configuration under the name `rates`; consumers inject `IHttpClientFactory` and call `CreateClient("rates")`, so the name is a magic string at every call site and the raw `HttpClient` leaks into callers. `AddHttpClient<ShippingRatesClient>(c => ...)` registers `ShippingRatesClient` as a **transient** service; the factory builds it with an `HttpClient` configured for the client name, which is the type's name without its namespace. Callers then inject `ShippingRatesClient` and call meaningful methods such as `GetQuoteAsync`, which keeps URLs, headers and JSON shapes in one class. Choose a typed client for a single downstream API you wrap; choose a named client when you need several configurations of the same shape, or when a singleton must create clients on demand. Since .NET 9, `.AddAsKeyed()` also exposes a named client as a keyed `HttpClient` service, scoped by default.
code
csharp · 17 linesbuilder.Services.AddHttpClient<IShippingRatesClient, ShippingRatesClient>(client =>
{
client.BaseAddress = new Uri("https://rates.example.com/");
});
public interface IShippingRatesClient
{
Task<RateQuote?> GetQuoteAsync(string zip, decimal weightKg, CancellationToken ct);
}
public sealed class ShippingRatesClient(HttpClient http) : IShippingRatesClient
{
public Task<RateQuote?> GetQuoteAsync(string zip, decimal weightKg, CancellationToken ct) =>
http.GetFromJsonAsync<RateQuote>($"v2/quotes?zip={zip}&kg={weightKg}", ct);
}
public record RateQuote(decimal Amount, string Currency);go deeper
Recall the two registration calls, CreateClient(name) for named clients, and that a typed client receives HttpClient in its constructor.
Explain that both resolve to one named configuration, that typed clients are transient and named after the type, and when each shape fits.
Show you avoid typed clients in singletons, handle name collisions with explicit names, and know AddAsKeyed's scoped default and its capture warnings.
Decide a team convention for wrapping downstream APIs, balancing typed-client encapsulation against named clients for multi-tenant or multi-region callers.
## Two ways to name a configuration Every `IHttpClientFactory` configuration is stored under a **logical name**. The base address, default headers, `Timeout`, extra `DelegatingHandler`s and the primary handler are all options keyed by that name, and the factory keeps one pooled handler chain per name. Named and typed clients differ only in how your code reaches that configuration. | | Named client | Typed client | |---|---|---| | Registration | `AddHttpClient("rates", c => ...)` | `AddHttpClient<ShippingRatesClient>(c => ...)` | | Client name | the string you pass | the type name without namespace, here `ShippingRatesClient` | | What consumers inject | `IHttpClientFactory` | `ShippingRatesClient` (or its interface) | | How they get a client | `CreateClient("rates")` on each use | the class receives an `HttpClient` in its constructor | | DI lifetime | the factory is a singleton | the typed client is **transient** | | Where API knowledge lives | spread over call sites | inside one class | ## Named clients A named client is the lighter option: - You register `builder.Services.AddHttpClient("rates", client => client.BaseAddress = new Uri("https://rates.example.com/"))`. - Consumers inject `IHttpClientFactory` and call `factory.CreateClient("rates")`; each call returns a new `HttpClient` over the pooled handler. - The name is a plain string, so a typo silently gives you an unconfigured client; a `const` field helps. - It is the right tool when **one code path needs several configurations** (two regions of the same provider, say), or when a **long-lived object** such as a singleton or a hosted service must create a fresh client per operation. ## Typed clients A typed client is a class you write that takes `HttpClient` in its constructor: 1. `AddHttpClient<ShippingRatesClient>(...)` registers the configuration under the name `ShippingRatesClient` and registers the class as a transient service. 2. When something resolves `ShippingRatesClient`, the factory calls `CreateClient("ShippingRatesClient")` and passes the result to the constructor through `ITypedHttpClientFactory<T>`. 3. The class exposes domain methods (`GetQuoteAsync(zip, weight, ct)`), so controllers and handlers never see URLs or JSON shapes. The interface form `AddHttpClient<IShippingRatesClient, ShippingRatesClient>()` registers the interface as the service, which makes consumers easy to test. If the class has no constructor that accepts an `HttpClient`, resolution fails with an `InvalidOperationException` saying a typed client must provide one. Because the client name is computed from the type name **without the namespace**, registering `Billing.RatesClient` and `Shipping.RatesClient` with the parameterless `AddHttpClient<T>()` throws an `InvalidOperationException` at registration; the fix is the overload that takes an explicit name. The transient lifetime is deliberate: a typed client is meant to be short-lived like the `HttpClient` inside it. Injecting one into a singleton keeps its handler chain past `HandlerLifetime`, which is the main trap of the typed approach. ## Configuration from options The configuration delegate has an overload that receives the `IServiceProvider`, which is how a client picks up settings bound from `appsettings.json` instead of hard-coding them: - `AddHttpClient<ShippingRatesClient>((sp, client) => { var o = sp.GetRequiredService<IOptions<RatesOptions>>().Value; client.BaseAddress = new Uri(o.BaseUrl); })`. - The delegate runs **every time** the factory creates a client for that name, so a typed client created later sees the values current at that moment. - Everything else is chained on the returned `IHttpClientBuilder`: `AddHttpMessageHandler<T>()` for delegating handlers, `ConfigurePrimaryHttpMessageHandler(...)` or `UseSocketsHttpHandler(...)` for the primary handler, `SetHandlerLifetime(...)` for rotation. Because all of this is keyed by the client name, a named and a typed client that happen to share a name also share configuration; giving every typed client its own type name avoids surprises. ## Keyed named clients (.NET 9 and later) `.AddAsKeyed()` on a named client's builder also registers that client as a **keyed service** with the client name as key: - Consumers write `[FromKeyedServices("rates")] HttpClient client` in a constructor or a Minimal API handler instead of injecting the factory. - The default lifetime is **scoped**; `AddAsKeyed(ServiceLifetime.Singleton)` or `Transient` are possible but carry warnings, because a singleton or captured client stops taking part in handler rotation. - Called on a typed client's builder, it makes only the underlying named client keyed; the typed class stays transient. - `RemoveAsKeyed()` opts a client back out. ## Choosing - One downstream API that the app talks to in several places: **typed client**. - Several similar configurations, or a singleton that needs clients: **named client**, created per use. - A handler or service that only needs the raw `HttpClient` and you want no factory in the signature: **named client with `AddAsKeyed()`**. Whatever you choose, the pooling, rotation and handler pipeline are identical, because all three resolve to the same named configuration.
- Why does registering Billing.RatesClient and Shipping.RatesClient with AddHttpClient<T>() fail?The parameterless typed overload names the client after the type without its namespace, so both compute the name `RatesClient`. The factory refuses to bind one name to two types and throws an `InvalidOperationException` at registration. Use the overload that takes a string name for at least one of them.
- Can a typed client depend on other services, such as IOptions<RatesOptions> or a logger?Yes. Its constructor takes the `HttpClient` plus any other services, and they are resolved from the same provider that resolves the typed client, for example the request scope. Only the message handlers live in the factory's separate handler scope.
- Says typed clients are registered as singletons so they can be reused
- Believes a named and a typed client use different connection pooling
- Thinks the typed client's name includes its namespace
- Believes AddAsKeyed registers the HttpClient as a singleton by default
- Says a typed client can be built without an HttpClient constructor parameter
Assumes ASP.NET Core 10 on .NET 10; AddAsKeyed for named clients arrived in .NET 9, so .NET 8 code must inject IHttpClientFactory or a typed client instead.