Phase 18 of 30 · Topic 18.3

.NET 8/9 Keyed Services (`[FromKeyedServices]`)

1Concept

Keyed Services allow multiple implementations of the same interface to be registered with distinct key identifiers (`string`, `enum`), eliminating custom factory dictionary hacks.

2Architecture Diagram

services.AddKeyedSingleton<IPaymentGateway, StripeGateway>("stripe");
services.AddKeyedSingleton<IPaymentGateway, PaypalGateway>("paypal");
       │
       ▼
public OrderService([FromKeyedServices("stripe")] IPaymentGateway payment) ──> Injects StripeGateway!

3Code Example

C# 13 & .NET 9
using System;
using Microsoft.Extensions.DependencyInjection;

public interface INotificationService { void Send(string message); }
public class SmsService : INotificationService { public void Send(string m) => Console.WriteLine($"SMS: {m}"); }
public class EmailService : INotificationService { public void Send(string m) => Console.WriteLine($"Email: {m}"); }

public class KeyedServicesDemo
{
    public static void Main()
    {
        var services = new ServiceCollection();
        services.AddKeyedSingleton<INotificationService, SmsService>("sms");
        services.AddKeyedSingleton<INotificationService, EmailService>("email");

        var provider = services.BuildServiceProvider();

        var sms = provider.GetRequiredKeyedService<INotificationService>("sms");
        var email = provider.GetRequiredKeyedService<INotificationService>("email");

        sms.Send("Verification Code: 4920");
        email.Send("Monthly Statement Ready.");
    }
}

4Expected Output

SMS: Verification Code: 4920
Email: Monthly Statement Ready.

5Key Takeaways

  • Keyed Services (.NET 8+) obsolete custom factory patterns.
  • Supports `GetRequiredKeyedService<T>(key)` and `[FromKeyedServices(key)]` in constructors.
  • Can use enums or strings as service registration keys.