Skip to content

Commit ba1042f

Browse files
CarnaViiregewarrenantonfirsov
authored
HttpClientFactory Keyed DI docs (#44533)
* (WIP) Keyed DI support in HCF * (WIP) * add xrefs and toc * fixes * lint * fix ref * Apply suggestions from code review Co-authored-by: Genevieve Warren <[email protected]> * remove foo * Apply suggestions from code review Co-authored-by: Anton Firszov <[email protected]> --------- Co-authored-by: Genevieve Warren <[email protected]> Co-authored-by: Anton Firszov <[email protected]>
1 parent ed74092 commit ba1042f

File tree

5 files changed

+408
-0
lines changed

5 files changed

+408
-0
lines changed
Lines changed: 302 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,302 @@
1+
---
2+
title: Keyed DI Support in IHttpClientFactory
3+
description: Learn how to integrate IHttpClientFactory with Keyed Services.
4+
author: CarnaViire
5+
ms.author: knatalia
6+
ms.date: 01/27/2025
7+
---
8+
9+
# Keyed DI support in `IHttpClientFactory`
10+
11+
In this article, you learn how to integrate `IHttpClientFactory` with Keyed Services.
12+
13+
[_Keyed Services_](dependency-injection.md#keyed-services) (also called _Keyed DI_) is a dependency injection (DI) feature that allows you to conveniently operate with multiple implementations of a single service. Upon registration, you can associate different _service keys_ with the specific implementations. At run time, this key is used in lookup in combination with a service type, which means you can retrieve a specific implementation by passing the matching key. For more information on Keyed Services, and DI in general, see [.NET dependency injection][di].
14+
15+
For an overview on how to use `IHttpClientFactory` in your .NET application, see [IHttpClientFactory with .NET][hcf].
16+
17+
## Background
18+
19+
`IHttpClientFactory` and Named `HttpClient` instances, unsurprisingly, align well with the Keyed Services idea. Historically, among other things, `IHttpClientFactory` was a way to overcome this long-missing DI feature. But plain Named clients require you to obtain, store, and query the `IHttpClientFactory` instance&mdash;instead of injecting a configured `HttpClient`&mdash;which might be inconvenient. While Typed clients attempt to simplify that part, it comes with a catch: Typed clients are easy to [misconfigure](httpclient-factory-troubleshooting.md#typed-client-has-the-wrong-httpclient-injected) and [misuse](httpclient-factory.md#avoid-typed-clients-in-singleton-services), and the supporting infrastructure can also be a tangible overhead in certain scenarios (for example, on mobile platforms).
20+
21+
Starting from .NET 9 (`Microsoft.Extensions.Http` and `Microsoft.Extensions.DependencyInjection` packages version `9.0.0+`), `IHttpClientFactory` can leverage Keyed DI directly, introducing a new "Keyed DI approach" (as opposed to "Named" and "Typed" approaches). "Keyed DI approach" pairs the convenient, highly configurable `HttpClient` registrations with the straightforward injection of the specific configured `HttpClient` instances.
22+
23+
## Basic Usage
24+
25+
As of .NET 9, you need to _opt in_ to the feature by calling the <xref:Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.AddAsKeyed%2A> extension method. If opted in, the Named client applying the configuration is added to the DI container as a Keyed `HttpClient` service, using the client's name as a service key, so you can use the standard Keyed Services APIs (for example, <xref:Microsoft.Extensions.DependencyInjection.FromKeyedServicesAttribute>) to obtain the desired Named `HttpClient` instances (created and configured by `IHttpClientFactory`). By default, the clients are registered with _Scoped_ lifetime.
26+
27+
The following code illustrates the integration between `IHttpClientFactory`, Keyed DI, and ASP.NET Core 9.0 Minimal APIs:
28+
29+
:::code source="snippets/http/keyedservices/Program.cs" highlight="4,10,16":::
30+
31+
Endpoint response:
32+
33+
```sh
34+
> ~ curl http://localhost:5000/
35+
{"name":"runtime","url":"https://api.github.com/repos/dotnet/runtime"}
36+
```
37+
38+
In the example, the configured `HttpClient` is injected into the request handler through the standard Keyed DI infrastructure, which is integrated into ASP.NET Core parameter binding. For more information on Keyed Services in ASP.NET Core, see [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection#keyed-services).
39+
40+
## Comparison of Keyed, Named, and Typed approaches
41+
42+
Consider only the `IHttpClientFactory`-related code from the [Basic Usage](#basic-usage) example:
43+
44+
```csharp
45+
services.AddHttpClient("github", /* ... */).AddAsKeyed(); // (1)
46+
47+
app.MapGet("/", ([FromKeyedServices("github")] HttpClient httpClient) => // (2)
48+
//httpClient.Get.... // (3)
49+
```
50+
51+
This code snippet illustrates how the registration `(1)`, obtaining the configured `HttpClient` instance `(2)`, and using the obtained client instance as needed `(3)` can look when using the _Keyed DI approach_.
52+
53+
Compare how the same steps are achieved with the two "older" approaches.
54+
55+
First, with the _Named approach_:
56+
57+
```csharp
58+
services.AddHttpClient("github", /* ... */); // (1)
59+
60+
app.MapGet("/github", (IHttpClientFactory httpClientFactory) =>
61+
{
62+
HttpClient httpClient = httpClientFactory.CreateClient("github"); // (2)
63+
//return httpClient.Get.... // (3)
64+
});
65+
```
66+
67+
Second, with the _Typed approach_:
68+
69+
```csharp
70+
services.AddHttpClient<GitHubClient>(/* ... */); // (1)
71+
72+
app.MapGet("/github", (GitHubClient gitHubClient) =>
73+
gitHubClient.GetRepoAsync());
74+
75+
public class GitHubClient(HttpClient httpClient) // (2)
76+
{
77+
private readonly HttpClient _httpClient = httpClient;
78+
79+
public Task<Repo> GetRepoAsync() =>
80+
//_httpClient.Get.... // (3)
81+
}
82+
```
83+
84+
Out of the three, the Keyed DI approach offers the most succinct way to achieve the same behavior.
85+
86+
## Built-in DI container validation
87+
88+
If you enabled the Keyed registration for a specific Named client, you can access it with any existing Keyed DI APIs. But if you erroneously try to use a name that isn't enabled yet, you get the standard Keyed DI exception:
89+
90+
```csharp
91+
services.AddHttpClient("keyed").AddAsKeyed();
92+
services.AddHttpClient("not-keyed");
93+
94+
provider.GetRequiredKeyedService<HttpClient>("keyed"); // OK
95+
96+
// Throws: No service for type 'System.Net.Http.HttpClient' has been registered.
97+
provider.GetRequiredKeyedService<HttpClient>("not-keyed");
98+
```
99+
100+
Additionally, the Scoped lifetime of the clients can help catch cases of captive dependencies:
101+
102+
```csharp
103+
services.AddHttpClient("scoped").AddAsKeyed();
104+
services.AddSingleton<CapturingSingleton>();
105+
106+
// Throws: Cannot resolve scoped service 'System.Net.Http.HttpClient' from root provider.
107+
rootProvider.GetRequiredKeyedService<HttpClient>("scoped");
108+
109+
using var scope = provider.CreateScope();
110+
scope.ServiceProvider.GetRequiredKeyedService<HttpClient>("scoped"); // OK
111+
112+
// Throws: Cannot consume scoped service 'System.Net.Http.HttpClient' from singleton 'CapturingSingleton'.
113+
public class CapturingSingleton([FromKeyedServices("scoped")] HttpClient httpClient)
114+
//{ ...
115+
```
116+
117+
## Service lifetime selection
118+
119+
By default, `AddAsKeyed()` registers `HttpClient` as a Keyed _Scoped_ service. You can also explicitly specify the lifetime by passing the `ServiceLifetime` parameter to the `AddAsKeyed()` method:
120+
121+
```csharp
122+
services.AddHttpClient("explicit-scoped")
123+
.AddAsKeyed(ServiceLifetime.Scoped);
124+
125+
services.AddHttpClient("singleton")
126+
.AddAsKeyed(ServiceLifetime.Singleton);
127+
```
128+
129+
If you call `AddAsKeyed()` within a Typed client registration, only the underlying Named client is registered as Keyed. The Typed client itself continues to be registered as a plain Transient service.
130+
131+
### Avoid transient HttpClient memory leak
132+
133+
> [!IMPORTANT]
134+
> `HttpClient` is `IDisposable`, so we strongly recommend _avoiding_ Transient lifetime for Keyed `HttpClient` instances.
135+
>
136+
> Registering the client as a Keyed Transient service leads to the `HttpClient` and `HttpMessageHandler` instances being _captured by DI container_, as both implement `IDisposable`. This can result in _memory leaks_ if the client is resolved multiple times within Singleton services.
137+
138+
### Avoid captive dependency
139+
140+
> [!IMPORTANT]
141+
> If `HttpClient` is registered either:
142+
>
143+
> - as a Keyed _Singleton_, -OR-
144+
> - as a Keyed _Scoped_ or _Transient_, and injected within a _long-running_ (longer than `HandlerLifetime`) application Scope, -OR-
145+
> - as a Keyed _Transient_, and injected into a _Singleton_ service,
146+
>
147+
> &mdash;the `HttpClient` instance becomes _captive_, and will likely outlive its expected `HandlerLifetime`. `IHttpClientFactory` has no control over captive clients, they're NOT able to participate in the handler rotation, and it can result in [the loss of DNS changes](httpclient-factory-troubleshooting.md#httpclient-doesnt-respect-dns-changes). A similar issue [already exists](httpclient-factory.md#avoid-typed-clients-in-singleton-services) for Typed clients, which are registered as Transient services.
148+
149+
In cases when client's longevity can't be avoided&mdash;or if it's consciously desired, for example, for a Keyed Singleton&mdash;it's advised to [leverage `SocketsHttpHandler`](httpclient-factory.md#using-ihttpclientfactory-together-with-socketshttphandler) by setting `PooledConnectionLifetime` to a reasonable value.
150+
151+
```csharp
152+
services.AddHttpClient("shared")
153+
.AddAsKeyed(ServiceLifetime.Singleton) // explicit singleton
154+
.UseSocketsHttpHandler((h, _) => h.PooledConnectionLifetime = TimeSpan.FromMinutes(2))
155+
.SetHandlerLifetime(Timeout.InfiniteTimeSpan); // disable rotation
156+
services.AddSingleton<MySingleton>();
157+
158+
public class MySingleton([FromKeyedServices("shared")] HttpClient shared) // { ...
159+
```
160+
161+
### Beware of scope mismatch
162+
163+
While Scoped lifetime is much less problematic for the Named `HttpClient`s (compared to Singleton and Transient pitfalls), it has its own catch.
164+
165+
> [!IMPORTANT]
166+
> Keyed Scoped lifetime of a specific `HttpClient` instance is bound&mdash;as expected&mdash;to the "ordinary" application scope (for example, incoming request scope) where it was resolved from. However, it does NOT apply to the underlying message handler chain, which is still managed by the `IHttpClientFactory`, in the same way it is for the Named clients created directly from factory. `HttpClient`s with the _same_ name, but resolved (within a `HandlerLifetime` timeframe) in two different scopes (for example, two concurrent requests to the same endpoint), can reuse the _same_ `HttpMessageHandler` instance. That instance, in turn, has its own separate scope, as illustrated in the [Message handler scopes](httpclient-factory.md#message-handler-scopes-in-ihttpclientfactory).
167+
168+
> [!NOTE]
169+
> The [Scope Mismatch](httpclient-factory-troubleshooting.md#httpclient-doesnt-respect-scoped-lifetime) problem is nasty and long-existing one, and as of .NET 9 still remains [unsolved](https://github.com/dotnet/runtime/issues/47091). From a service injected through the regular DI infra, you would expect all the dependencies to be satisfied from the same scope&mdash;but for the Keyed Scoped `HttpClient` instances, that's unfortunately not the case.
170+
171+
## Keyed message handler chain
172+
173+
For some advanced scenarios, you might want to access `HttpMessageHandler` chain directly, instead of an `HttpClient` object. `IHttpClientFactory` provides `IHttpMessageHandlerFactory` interface to create the handlers; and if you enable Keyed DI, then not only `HttpClient`, but also the respective `HttpMessageHandler` chain is registered as a Keyed service:
174+
175+
```csharp
176+
services.AddHttpClient("keyed-handler").AddAsKeyed();
177+
178+
var handler = provider.GetRequiredKeyedService<HttpMessageHandler>("keyed-handler");
179+
var invoker = new HttpMessageInvoker(handler, disposeHandler: false);
180+
```
181+
182+
## How to: Switch from Typed approach to Keyed DI
183+
184+
> [!NOTE]
185+
> We currently recommend using Keyed DI approach instead of Typed clients.
186+
187+
A minimal-change switch from an existing Typed client to a Keyed dependency can look as follows:
188+
189+
```diff
190+
- services.AddHttpClient<Service>( // (1) Typed client
191+
+ services.AddHttpClient(nameof(Service), // (1) Named client
192+
c => { /* ... */ } // HttpClient configuration
193+
//).Configure....
194+
- );
195+
+ ).AddAsKeyed(); // (1) + Keyed DI opt-in
196+
197+
+ services.AddTransient<Service>(); // (1) Plain Transient service
198+
199+
public class Service(
200+
- // (2) "Hidden" Named dependency
201+
+ [FromKeyedServices(nameof(Service))] // (2) Explicit Keyed dependency
202+
HttpClient httpClient) // { ...
203+
```
204+
205+
In the example:
206+
207+
1. The registration of the Typed client `Service` is split into:
208+
- A registration of a Named client `nameof(Service)` with the same `HttpClient` configuration, and an opt-in to Keyed DI; and
209+
- Plain Transient service `Service`.
210+
2. `HttpClient` dependency in `Service` is explicitly bound to a Keyed Service with a key `nameof(Service)`.
211+
212+
The name doesn't have to be `nameof(Service)`, but the example aimed to minimize the behavioral changes. Internally, typed clients use Named clients, and by default, such "hidden" Named clients go by the linked Typed client's type name. In this case, the "hidden" name was `nameof(Service)`, so the example preserved it.
213+
214+
Technically, the example "unwraps" the Typed client, so that the previously "hidden" Named client becomes "exposed," and the dependency is satisfied via the Keyed DI infra instead of the Typed client infra.
215+
216+
## How to: Opt in to Keyed DI by default
217+
218+
You don't have to call <xref:Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.AddAsKeyed%2A> for every single client&mdash;you can easily opt in "globally" (for any client name) via <xref:Microsoft.Extensions.DependencyInjection.HttpClientFactoryServiceCollectionExtensions.ConfigureHttpClientDefaults%2A>. From Keyed Services perspective, it results in the <xref:Microsoft.Extensions.DependencyInjection.KeyedService.AnyKey?displayProperty=nameWithType> registration.
219+
220+
```csharp
221+
services.ConfigureHttpClientDefaults(b => b.AddAsKeyed());
222+
223+
services.AddHttpClient("first", /* ... */);
224+
services.AddHttpClient("second", /* ... */);
225+
services.AddHttpClient("third", /* ... */);
226+
227+
public class MyController(
228+
[FromKeyedServices("first")] HttpClient first,
229+
[FromKeyedServices("second")] HttpClient second,
230+
[FromKeyedServices("third")] HttpClient third)
231+
//{ ...
232+
```
233+
234+
### Beware Of "Unknown" clients
235+
236+
> [!NOTE]
237+
> `KeyedService.AnyKey` registrations define a mapping from _any_ key value to some service instance. However, as a result, the Container validation doesn't apply, and an _erroneous_ key value _silently_ leads to a _wrong instance_ being injected.
238+
239+
> [!IMPORTANT]
240+
> For Keyed `HttpClient`s, a mistake in the client name can result in erroneously injecting an "unknown" client&mdash;meaning, a client whose name was never registered.
241+
242+
The same is true for the plain Named clients: `IHttpClientFactory` doesn't require the client name to be explicitly registered (aligning with the way the [Options pattern](options.md) works). The factory gives you an unconfigured&mdash;or, more precisely, default-configured&mdash;`HttpClient` for any unknown name.
243+
244+
> [!NOTE]
245+
> Therefore, it's important to keep in mind: the "Keyed by default" approach covers not only all _registered_ `HttpClient`s, but all the clients that `IHttpClientFactory` is _able to create_.
246+
247+
```csharp
248+
services.ConfigureHttpClientDefaults(b => b.AddAsKeyed());
249+
services.AddHttpClient("known", /* ... */);
250+
251+
provider.GetRequiredKeyedService<HttpClient>("known"); // OK
252+
provider.GetRequiredKeyedService<HttpClient>("unknown"); // OK (unconfigured instance)
253+
```
254+
255+
### "Opt-in" strategy considerations
256+
257+
Even though the "global" opt-in is a one-liner, it's unfortunate that the feature still requires it, instead of just working "out of the box." For full context and reasoning on that decision, see [dotnet/runtime#89755](https://github.com/dotnet/runtime/issues/89755) and [dotnet/runtime#104943](https://github.com/dotnet/runtime/pull/104943). In short, the main blocker for "on by default" is the `ServiceLifetime` "controversy": for the current (`9.0.0`) state of the DI and `IHttpClientFactory` implementations, there's no single `ServiceLifetime` that would be reasonably safe for all `HttpClient`s in all possible situations. There's an intention, however, to address the caveats in the upcoming releases, and switch the strategy from "opt-in" to "opt-out".
258+
259+
## How to: Opt out from keyed registration
260+
261+
You can explicitly opt out from Keyed DI for `HttpClient`s by calling the <xref:Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.RemoveAsKeyed%2A> extension method, either per client name:
262+
263+
```csharp
264+
services.ConfigureHttpClientDefaults(b => b.AddAsKeyed()); // opt IN by default
265+
services.AddHttpClient("keyed", /* ... */);
266+
services.AddHttpClient("not-keyed", /* ... */).RemoveAsKeyed(); // opt OUT per name
267+
268+
provider.GetRequiredKeyedService<HttpClient>("keyed"); // OK
269+
provider.GetRequiredKeyedService<HttpClient>("not-keyed"); // Throws: No service for type 'System.Net.Http.HttpClient' has been registered.
270+
provider.GetRequiredKeyedService<HttpClient>("unknown"); // OK (unconfigured instance)
271+
```
272+
273+
Or "globally" with <xref:Microsoft.Extensions.DependencyInjection.HttpClientFactoryServiceCollectionExtensions.ConfigureHttpClientDefaults%2A>:
274+
275+
```csharp
276+
services.ConfigureHttpClientDefaults(b => b.RemoveAsKeyed()); // opt OUT by default
277+
services.AddHttpClient("keyed", /* ... */).AddAsKeyed(); // opt IN per name
278+
services.AddHttpClient("not-keyed", /* ... */);
279+
280+
provider.GetRequiredKeyedService<HttpClient>("keyed"); // OK
281+
provider.GetRequiredKeyedService<HttpClient>("not-keyed"); // Throws: No service for type 'System.Net.Http.HttpClient' has been registered.
282+
provider.GetRequiredKeyedService<HttpClient>("unknown"); // Throws: No service for type 'System.Net.Http.HttpClient' has been registered.
283+
```
284+
285+
## Order of precedence
286+
287+
If called together or any of them more than once, `AddAsKeyed()` and `RemoveAsKeyed()` generally follow the rules of `IHttpClientFactory` configs and DI registrations:
288+
289+
1. If called for the same name, the last setting wins: the lifetime from the last `AddAsKeyed()` is used to create the Keyed registration (unless `RemoveAsKeyed()` was called last, in which case the name is excluded).
290+
2. If used only within `ConfigureHttpClientDefaults`, the last setting wins.
291+
3. If both `ConfigureHttpClientDefaults` and specific client name were used, all defaults are considered to "happen" before all per-name settings. Thus, defaults can be disregarded, and the last of the per-name settings wins.
292+
293+
## See also
294+
295+
- [IHttpClientFactory with .NET][hcf]
296+
- [Dependency injection in .NET][di]
297+
- <xref:System.Net.Http.IHttpClientFactory>
298+
- [Common `IHttpClientFactory` usage issues][hcf-troubleshooting]
299+
300+
[hcf]: httpclient-factory.md
301+
[di]: dependency-injection.md
302+
[hcf-troubleshooting]: httpclient-factory-troubleshooting.md

0 commit comments

Comments
 (0)