How to Use Keyed Services in .NET Dependency Injection for Multiple Implementations

Before .NET 8, injecting two different implementations of the same interface—such as an email notifier and an SMS notifier implementing INotifier, or two named HttpClient configurations—usually meant writing custom factory classes, injecting IEnumerable<INotifier> and filtering with .First(...), or pulling in a third-party IoC container. Since .NET 8, Microsoft.Extensions.DependencyInjection includes Keyed Services natively, letting you register and inject specific implementations by key.

Editorial illustration of Keyed Services in .NET Dependency Injection

Editorial illustration: register implementations with AddKeyed* and resolve the exact one needed with [FromKeyedServices].

Summary

  • Keyed Services (introduced in .NET 8 in Microsoft.Extensions.DependencyInjection) let you associate a key (string, enum, or any object) with a service registration via AddKeyedSingleton, AddKeyedScoped, or AddKeyedTransient.
  • Inject a specific keyed implementation into constructors, Minimal API endpoints, or MVC controllers using the [FromKeyedServices("key")] attribute, as documented in Microsoft Learn’s ASP.NET Core Dependency Injection guide.
  • IHttpClientFactory also supports keyed DI via AddAsKeyed() so typed HTTP clients can be resolved cleanly by key.
  • Avoid overusing keyed services when distinct interfaces (such as IEmailNotifier and ISmsNotifier) make dependencies clearer at compile time.

Prerequisites: .NET DI Container vs. C# Language

  • .NET Runtime / Extensions (Microsoft.Extensions.DependencyInjection): Keyed services were added in .NET 8 and are available across .NET 8, .NET 9, .NET 10, and .NET 11 in console Worker Services, Minimal APIs, MVC, SignalR, and Blazor.
  • C# Language & IDE: Primary constructors (C# 12+) make [FromKeyedServices] especially concise in Visual Studio 2022/2026 or VS Code with the .NET SDK.

Practical example: Register and inject keyed services

Suppose an order service sends urgent alerts via SMS and standard receipts via email, both implementing INotifier:

using Microsoft.Extensions.DependencyInjection;

public interface INotifier
{
    Task SendAsync(string recipient, string message, CancellationToken ct);
}

public sealed class EmailNotifier : INotifier
{
    public Task SendAsync(string recipient, string message, CancellationToken ct)
        => Task.CompletedTask;
}

public sealed class SmsNotifier : INotifier
{
    public Task SendAsync(string recipient, string message, CancellationToken ct)
        => Task.CompletedTask;
}

Register both implementations in Program.cs with AddKeyedSingleton (or AddKeyedScoped / AddKeyedTransient depending on lifetime):

builder.Services.AddKeyedSingleton<INotifier, EmailNotifier>("email");
builder.Services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");

Then inject the exact implementation you need using [FromKeyedServices(...)]:

public sealed class SecurityAlertService(
    [FromKeyedServices("sms")] INotifier urgentNotifier,
    [FromKeyedServices("email")] INotifier auditNotifier)
{
    public async Task NotifyAsync(string phone, string email, CancellationToken ct)
    {
        await urgentNotifier.SendAsync(phone, "Suspicious login detected.", ct);
        await auditNotifier.SendAsync(email, "Security alert logged.", ct);
    }
}

In Minimal APIs, [FromKeyedServices("sms")] also works directly as an endpoint parameter—no custom factory wrapper needed.

Dynamic lookup at runtime with IKeyedServiceProvider

When the key is only known at runtime (for example, from a user preference "sms" vs. "email"), avoid calling IServiceProvider directly across domain classes; instead, wrap IKeyedServiceProvider.GetRequiredKeyedService<INotifier>(channel) inside a small, well-tested dispatcher service so invalid keys fail with a clear domain error.

Using KeyedService.AnyKey for fallback registrations

Per Microsoft Learn’s .NET dependency injection overview, KeyedService.AnyKey provides a wildcard key for registering a fallback implementation when no specific key matches—helpful for multi-tenant defaults when most tenants share a standard implementation and only two tenants need overrides.

When NOT to use Keyed Services

Keyed services solve real boilerplate, yet they trade compile-time type safety for a runtime key lookup:

  • If two services have genuinely different contracts, define separate interfaces (IEmailSender vs. ISmsSender) instead of forcing both behind INotifier with magic strings.
  • If you need all implementations at once (for example, running every registered validator or event handler), standard IEnumerable<IValidator> injection is cleaner without keys.

For related .NET service patterns, see using PeriodicTimer in BackgroundService workers and using FrozenDictionary for fast read-only lookups.

Common mistakes

  • Using magic strings scattered across 15 files. Define constants or an enum (e.g., NotificationChannel.Sms) so a typo fails at compile time instead of throwing InvalidOperationException at runtime.
  • Mixing AddSingleton<INotifier, ...>() with [FromKeyedServices("email")]. A non-keyed registration does not satisfy a [FromKeyedServices] parameter (and vice versa) unless explicitly registered for both.
  • Calling [FromKeyedServices] on a scoped service injected into a singleton. Keyed registrations still obey .NET’s captive-dependency rules—do not inject a KeyedScoped service into a Singleton!

Why this matters

Using built-in keyed services replaces fragile IEnumerable<T> .First() hacks and repetitive factory boilerplate with a single, standard .NET DI feature that works consistently across Minimal APIs, controllers, SignalR, and IHttpClientFactory.

My Take

Reach for Keyed Services when you truly have multiple implementations of the same abstraction—like storage providers, regional payment gateways, or named HttpClient integrations. Keep keys in constants or enums, and stick to distinct interfaces whenever two services serve different responsibilities.

Conclusion

Register multiple implementations of a shared interface using AddKeyedSingleton, AddKeyedScoped, or AddKeyedTransient, resolve them cleanly with [FromKeyedServices(MyKeys.Sms)], keep keys strongly typed with constants or enums, and verify service lifetimes against captive dependencies.

Sources