Advertisement
Advanced ASP.NET Core, Dependency Injection

What are keyed services (introduced in .NET 8), and what problem do they solve compared to injecting IEnumerable<T> when you need one specific implementation?

Short answer

Keyed services let you register multiple implementations of the same interface under distinct string or object keys, resolved explicitly via [FromKeyedServices("key")] or GetRequiredKeyedService(key) -- solving the ambiguity of IEnumerable injection (which gives you everything…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Keyed services let you register multiple implementations of the same interface under distinct string or object keys, resolved explicitly via [FromKeyedServices("key")] or GetRequiredKeyedService(key) -- solving the ambiguity of IEnumerable<T> injection (which gives you everything, requiring filtering) when you actually need one specific, named implementation deterministically, without a hand-rolled factory pattern or string-based service locator.
builder.Services.AddKeyedScoped<IPaymentProcessor, StripeProcessor>("stripe");
builder.Services.AddKeyedScoped<IPaymentProcessor, PayPalProcessor>("paypal");

public class CheckoutService([FromKeyedServices("stripe")] IPaymentProcessor 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 without needing a custom factory class or dictionary-based lookup that keyed services now handle natively.
Likely 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?
Related topics