In ASP.NET Core 10, how do you choose among three keyed IPaymentGateway registrations per request, and what can go wrong with the key?
answer
- AddKeyedScoped with a key object
- inject IServiceProvider, resolve by key
- GetRequiredKeyedService<T>(key)
- keys compared with Equals
- KeyedService.AnyKey as a fallback
basics
~10 sRegister each gateway with AddKeyedScoped<IPaymentGateway, T>(key), then resolve at runtime with GetRequiredKeyedService<IPaymentGateway>(order.Provider) from the request's IServiceProvider. Keys match by Equals, so case or type mismatches throw InvalidOperationException.
solid answer
~40 sSince .NET 8 the built-in container supports **keyed services**: `AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe")` and the same for PayPal and Adyen. A key fixed at compile time is injected with `[FromKeyedServices("stripe")]`, but a provider stored on the order is only known at runtime, so a scoped resolver injects `IServiceProvider` (the request scope, which implements `IKeyedServiceProvider`) and calls `GetRequiredKeyedService<IPaymentGateway>(order.Provider)`. Keys are compared with `Equals`, so `"Stripe"` does not match `"stripe"` and an enum key never matches a string; a miss throws `InvalidOperationException` ("No keyed service for type ... using key type 'System.String' has been registered"), while `GetKeyedService` returns null. Keyed registrations are invisible to plain `IPaymentGateway` and `IEnumerable<IPaymentGateway>`. In .NET 10, resolving a single service with `KeyedService.AnyKey` throws.
code
csharp · 16 linesbuilder.Services.AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe");
builder.Services.AddKeyedScoped<IPaymentGateway, PayPalGateway>("paypal");
builder.Services.AddKeyedScoped<IPaymentGateway, AdyenGateway>("adyen");
builder.Services.AddScoped<PaymentGatewayResolver>();
public sealed class PaymentGatewayResolver(
IServiceProvider services, IServiceProviderIsKeyedService keyed)
{
public IPaymentGateway For(string provider)
{
var key = provider.ToLowerInvariant();
if (!keyed.IsKeyedService(typeof(IPaymentGateway), key))
throw new ArgumentOutOfRangeException(nameof(provider), provider, "Unknown provider");
return services.GetRequiredKeyedService<IPaymentGateway>(key);
}
}go deeper
Recall the AddKeyedScoped registration and that a key picks one implementation of an interface; know that keyed services exist since .NET 8.
Explain resolving by a runtime key with GetRequiredKeyedService, why keys compare with Equals, and that keyed and unkeyed registrations never see each other.
Treat the key as untrusted input: normalise, validate with IsKeyedService, map misses to a 400, and confine service location to a resolver. Know the .NET 10 AnyKey change.
Decide when keyed registrations beat a strategy dictionary or a factory class, considering discoverability, testing and how new providers get onboarded.
## Registering the three gateways **Keyed services** arrived in the built-in container in .NET 8. A key is any object (a string, an enum value, a constant) attached to a registration: ```csharp builder.Services.AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"); builder.Services.AddKeyedScoped<IPaymentGateway, PayPalGateway>("paypal"); builder.Services.AddKeyedScoped<IPaymentGateway, AdyenGateway>("adyen"); ``` Each key gets its own cache, so within one request `"stripe"` always returns the same `StripeGateway` and never the `PayPalGateway`. `AddKeyedSingleton` and `AddKeyedTransient` work the same way, and each has a factory overload that also receives the key: `Func<IServiceProvider, object?, TService>`. ## Choosing the gateway per request In the artisan marketplace, each order records which provider took the payment, and refunds must go back through that same provider. The key is therefore data, known only at runtime. - A **fixed** key is injected with the `[FromKeyedServices("stripe")]` attribute on a constructor parameter. That is the right tool when a class always needs one specific gateway. - A **runtime** key needs a lookup. Inject `IServiceProvider` into a scoped resolver class. Inside a request it is the request scope, which implements `IKeyedServiceProvider`, and the extension method `GetRequiredKeyedService<IPaymentGateway>(key)` calls it. `IKeyedServiceProvider` itself is not registered as an injectable service; ask for `IServiceProvider`. Wrapping the lookup in a small `PaymentGatewayResolver` keeps service location in one class, so the rest of the code receives an `IPaymentGateway` and stays testable. ## What goes wrong with the key | Mistake | Result | |---|---| | Key `"Stripe"` looked up, `"stripe"` registered | no match: string keys use `Equals`, which is case-sensitive | | `PaymentProvider.Stripe` enum looked up, `"stripe"` string registered | no match: different key types never compare equal | | Unknown key with `GetRequiredKeyedService` | `InvalidOperationException`: "No keyed service for type 'IPaymentGateway' using key type 'System.String' has been registered." | | Unknown key with `GetKeyedService` | returns `null` | | Plain `IPaymentGateway` requested | not found: unkeyed lookups never see keyed registrations | Because the key often comes from stored or user-supplied data, normalise it (for example `ToLowerInvariant()`, or parse into an enum) and check it before resolving. `IServiceProviderIsKeyedService.IsKeyedService(typeof(IPaymentGateway), key)` answers whether a registration exists, so an unknown provider can become a `400` instead of a `500`. ## AnyKey and enumerating keyed services `KeyedService.AnyKey` has two uses: 1. As a **registration key** it is a fallback: `AddKeyedScoped<IPaymentGateway, ManualInvoiceGateway>(KeyedService.AnyKey)` serves any key that has no exact registration. A constructor parameter marked `[ServiceKey]` receives the key the instance was resolved for, so one class can serve many keys. With such a fallback, `IsKeyedService` returns true for every key. 2. As a **lookup key** for many services: `GetKeyedServices<IPaymentGateway>(KeyedService.AnyKey)` returns the registrations that have a specific key. .NET 10 tightened both lookups. `GetKeyedService` or `GetRequiredKeyedService` with `KeyedService.AnyKey` for a **single** service now throws `InvalidOperationException` ("KeyedService.AnyKey cannot be used to resolve a single service"). Before .NET 10 it returned the `AnyKey` registration. `GetKeyedServices` with `AnyKey` no longer includes registrations made with `AnyKey` itself. ## Lifetimes and testing The lifetime belongs to each keyed registration, so the three gateways can differ: a stateless `AdyenGateway` can be `AddKeyedSingleton` while `StripeGateway` stays scoped. Two practical consequences: - A scoped keyed gateway resolved through the request's `IServiceProvider` is disposed with the request, like any scoped service. Resolving it from `app.Services` (the root provider) outside a request is the same mistake as for unkeyed scoped services. - In tests, register a fake under the same key, for example `AddKeyedScoped<IPaymentGateway, FakeGateway>("stripe")` after the real one. Last-wins applies **per key**, so the fake replaces only the Stripe gateway and the other two stay real. ## Summary - Register per provider with `AddKeyedScoped`. - Resolve per order with `GetRequiredKeyedService` behind a resolver. - Treat the key as untrusted input: normalise it and check it. - Remember that keyed and unkeyed registrations never mix.
- How does one class serve several keys and still know which key it was resolved for?Register it under each key, or once under `KeyedService.AnyKey`, and add a constructor parameter marked `[ServiceKey]`. The container passes the lookup key into that parameter. The parameter type must match the key's type or be `object`, otherwise activation throws `InvalidOperationException`.
- Why prefer a resolver class over injecting IServiceProvider into every service that needs a gateway?The runtime lookup is service location, which hides dependencies and makes tests build a whole provider. Confining it to one `PaymentGatewayResolver` keeps key normalisation and validation in one place, while every other class depends on the resolver or receives an `IPaymentGateway`, both easy to fake.
- What changed for KeyedService.AnyKey lookups in .NET 10?Resolving a single service with `KeyedService.AnyKey` now throws `InvalidOperationException`, where earlier versions returned the registration made with `AnyKey`. `GetKeyedServices` with `AnyKey` still enumerates the services registered under specific keys, but no longer includes the `AnyKey` registrations themselves.
- String keys are matched case-insensitively, so "Stripe" finds the "stripe" registration.
- A constructor asking for plain IPaymentGateway receives one of the keyed registrations.
- GetRequiredKeyedService returns null when the key is not registered.
- Inject IKeyedServiceProvider directly into the resolver's constructor.
- GetKeyedService with KeyedService.AnyKey returns the fallback gateway on .NET 10.
Assumes ASP.NET Core 10 on .NET 10: keyed services date from .NET 8, and since .NET 10 resolving a single service with KeyedService.AnyKey throws instead of returning the AnyKey registration.