.NET › Dependency Injection
What are keyed services (introduced in .NET 8), and what problem do they solve compared to multiple unnamed registrations?
AdvancedAnswer
Keyed services let you register multiple implementations of the same interface under distinct string or object keys, then resolve a specific one explicitly using [FromKeyedServices("key")] or GetRequiredKeyedService(key) -- solving the ambiguity problem of IEnumerable<T> injection (which gives you everything, requiring you to filter or iterate) when you actually need one specific, named implementation deterministically, without resorting to a factory pattern or string-based service locator anti-pattern.
builder.Services.AddKeyedScoped<IPaymentProcessor, StripeProcessor>("stripe");
builder.Services.AddKeyedScoped<IPaymentProcessor, PayPalProcessor>("paypal");
public class CheckoutService {
public CheckoutService([FromKeyedServices("stripe")] IPaymentProcessor processor) {
_processor = processor; // explicitly gets the Stripe implementation
}
}Real-world example A multi-payment-provider e-commerce platform uses keyed services to explicitly wire different checkout flows to specific payment processors (stripe, paypal, applepay) without needing a custom factory class or dictionary-based lookup that keyed services now handle natively.