Back to results for “Dependency Injection”
.NET › Dependency Injection

What are keyed services (introduced in .NET 8), and what problem do they solve compared to multiple unnamed registrations?

Advanced

Answer

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.

Common follow-ups: How do keyed services interact with IEnumerable<T> injection -- can you still get all of them?;What's the migration path from a hand-rolled factory pattern to keyed services?