To use keyed services in ASP.NET Core, register each implementation under its own key with AddKeyedSingleton (or the Scoped and Transient versions), then ask for one by key with [FromKeyedServices]:
builder.Services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");
app.MapGet("/notify/sms", ([FromKeyedServices("sms")] INotifier notifier) =>
notifier.Send("(512) 555-0147", "Order #4821 shipped"));
I tested all of it on .NET 10 with a small order-notification API on localhost, including the exact exception you get when you ask for a key nobody registered.
What Are Keyed Services in .NET Dependency Injection?
Keyed services let you register several implementations of one C# interface and pick one by a key. Before .NET 8 the built-in container had no way to do that, so you wrote a factory or a name lookup.
A registration is now identified by the service type plus the key. Here’s the whole API on one screen:
| Task | API | Since |
|---|---|---|
| Register | AddKeyedSingleton, AddKeyedScoped, AddKeyedTransient | .NET 8 |
| Inject a parameter | [FromKeyedServices("sms")] | .NET 8 |
| Resolve in code | GetRequiredKeyedService, GetKeyedService, GetKeyedServices | .NET 8 |
| Receive the key | [ServiceKey] on a constructor parameter | .NET 8 |
| Fallback for any key | KeyedService.AnyKey | .NET 8 |
| Blazor component | [Inject(Key = "sms")] | .NET 8 |
| Keyed HttpClient | AddAsKeyed() | .NET 9 |
My running sample is an online store that tells customers about orders. All the console demos share this Notifiers.cs file through #:include:
public interface INotifier
{
string Send(string to, string text);
}
public class SmsNotifier : INotifier
{
public string Send(string to, string text) => $"SMS to {to}: {text}";
}
public class EmailNotifier : INotifier
{
public string Send(string to, string text) => $"Email to {to}: {text}";
}
public class PushNotifier : INotifier
{
public string Send(string to, string text) => $"Push to {to}: {text}";
}
Register Keyed Services with AddKeyedSingleton and Resolve Them
In a console app you build a ServiceCollection yourself (my guide to dependency injection in a C# console app shows the host version). This file-based app needs one package, Microsoft.Extensions.DependencyInjection 10.0.14:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");
services.AddKeyedSingleton<INotifier, EmailNotifier>("email");
using var provider = services.BuildServiceProvider();
var sms = provider.GetRequiredKeyedService<INotifier>("sms");
Console.WriteLine(sms.Send("(512) 555-0147", "Order #4821 shipped"));
var email = provider.GetRequiredKeyedService<INotifier>("email");
Console.WriteLine(email.Send("jenna.morales@example.com", "Order #4821 shipped"));
Console.WriteLine($"GetKeyedService(\"fax\"): {provider.GetKeyedService<INotifier>("fax")?.ToString() ?? "null"}");
Console.WriteLine($"GetService (no key): {provider.GetService<INotifier>()?.ToString() ?? "null"}");
Console.WriteLine($"IKeyedServiceProvider: {provider is IKeyedServiceProvider}");
Output:
SMS to (512) 555-0147: Order #4821 shipped
Email to jenna.morales@example.com: Order #4821 shipped
GetKeyedService("fax"): null
GetService (no key): null
IKeyedServiceProvider: True

GetRequiredKeyedService returns the right class for each key. GetKeyedService("fax") returns null instead of throwing, which is the one to use when a missing key is normal.
Note: GetService<INotifier>() without a key also printed null, because keyed registrations are invisible to normal resolution. These methods live on IKeyedServiceProvider.
AddKeyedScoped and AddKeyedTransient
The lifetime rules don’t change when you add a key. Same three notifiers, one per lifetime, each resolved twice inside one scope:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");
services.AddKeyedScoped<INotifier, EmailNotifier>("email");
services.AddKeyedTransient<INotifier, PushNotifier>("push");
using var provider = services.BuildServiceProvider();
using var scope = provider.CreateScope();
foreach (var key in new[] { "sms", "email", "push" })
{
var first = scope.ServiceProvider.GetRequiredKeyedService<INotifier>(key);
var second = scope.ServiceProvider.GetRequiredKeyedService<INotifier>(key);
Console.WriteLine($"{key,-5} same instance in one scope: {ReferenceEquals(first, second)}");
}
Output:
sms same instance in one scope: True
email same instance in one scope: True
push same instance in one scope: False
The singleton and scoped ones returned the same instance twice; the transient one didn’t. The full rules are in my post on ASP.NET Core DI lifetimes, so I won’t repeat them.
[FromKeyedServices] in Minimal API Endpoints
In ASP.NET Core the registrations go on builder.Services. Here’s the whole API I tested on localhost:5933, with two minimal API endpoints and one controller:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");
builder.Services.AddKeyedSingleton<INotifier, EmailNotifier>("email");
builder.Services.AddControllers();
var app = builder.Build();
// 1. Minimal API: the key is fixed at compile time
app.MapGet("/notify/sms", ([FromKeyedServices("sms")] INotifier notifier) =>
notifier.Send("(512) 555-0147", "Order #4821 shipped"));
// 2. Minimal API: the key comes from the URL, so resolve it at run time
app.MapGet("/notify/{channel}", (string channel, IServiceProvider sp) =>
sp.GetKeyedService<INotifier>(channel) is { } notifier
? Results.Text(notifier.Send("tyler.brooks@example.com", "Refund issued"))
: Results.NotFound($"No notifier registered for '{channel}'"));
app.MapControllers();
Console.WriteLine("Notification API on http://localhost:5933");
app.Run("http://localhost:5933");
// 3. Controller: primary constructor + action parameter
[ApiController]
[Route("orders")]
public class OrdersController([FromKeyedServices("email")] INotifier email) : ControllerBase
{
[HttpPost("{id}/ship")]
public string Ship(int id) =>
email.Send("jenna.morales@example.com", $"Order #{id} shipped");
[HttpGet("{id}/text")]
public string Text(int id, [FromKeyedServices("sms")] INotifier sms) =>
sms.Send("(512) 555-0147", $"Order #{id} is out for delivery");
}
Endpoint 1 binds the sms notifier with [FromKeyedServices]. Endpoint 2 takes the key from the URL, so it resolves it at run time from IServiceProvider and returns 404 when the key is unknown.
A small client calls all of them:
#!/usr/bin/env dotnet
#:property PublishAot=false
using var http = new HttpClient { BaseAddress = new Uri("http://localhost:5933/") };
foreach (var path in new[] { "notify/sms", "notify/email", "notify/fax" })
{
var res = await http.GetAsync(path);
Console.WriteLine($"GET {path} -> {(int)res.StatusCode} {await res.Content.ReadAsStringAsync()}");
}
var ship = await http.PostAsync("orders/4821/ship", null);
Console.WriteLine($"POST orders/4821/ship -> {await ship.Content.ReadAsStringAsync()}");
Console.WriteLine($"GET orders/4821/text -> {await http.GetStringAsync("orders/4821/text")}");
Output:
GET notify/sms -> 200 SMS to (512) 555-0147: Order #4821 shipped
GET notify/email -> 200 Email to tyler.brooks@example.com: Refund issued
GET notify/fax -> 404 "No notifier registered for 'fax'"
POST orders/4821/ship -> Email to jenna.morales@example.com: Order #4821 shipped
GET orders/4821/text -> SMS to (512) 555-0147: Order #4821 is out for delivery

notify/fax returned 404 with my message, because GetKeyedService gave back null. Both styles bind keyed services the same way; my minimal APIs vs controllers comparison covers when to pick each.
Inject Keyed Services into Controllers and Primary Constructors
In OrdersController above, [FromKeyedServices] sits on a C# 12 primary constructor parameter, so the class header is the whole injection. The Text action puts it on an action parameter instead, so only that action gets the SMS notifier.
The same attribute works in SignalR hubs and custom middleware, in the constructor or in InvokeAsync.
Keyed Services vs the Old Factory Delegate Way
Before .NET 8, the common trick was a Func<string, INotifier> with a switch expression that maps names to concrete types. It still works:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddSingleton<SmsNotifier>();
services.AddSingleton<EmailNotifier>();
services.AddSingleton<Func<string, INotifier>>(sp => channel => channel switch
{
"sms" => sp.GetRequiredService<SmsNotifier>(),
"email" => sp.GetRequiredService<EmailNotifier>(),
_ => throw new ArgumentException($"Unknown channel: {channel}")
});
using var provider = services.BuildServiceProvider();
var pick = provider.GetRequiredService<Func<string, INotifier>>();
Console.WriteLine(pick("sms").Send("(512) 555-0147", "Order #4821 shipped"));
Console.WriteLine(pick("email").Send("jenna.morales@example.com", "Order #4821 shipped"));
Output:
SMS to (512) 555-0147: Order #4821 shipped
Email to jenna.morales@example.com: Order #4821 shipped
Same output as the keyed version, but you register every concrete class, keep the switch in sync by hand, and consumers depend on a Func instead of the interface. With keys, the two AddKeyedSingleton lines replace all of it.
Enum Keys vs String Keys for Keyed Services
The key can be any object with a sensible Equals. An enum gives you compile-time checking, so a typo can’t slip into a key:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddKeyedSingleton<INotifier, SmsNotifier>(Channel.Sms);
services.AddKeyedSingleton<INotifier, EmailNotifier>(Channel.Email);
using var provider = services.BuildServiceProvider();
var email = provider.GetRequiredKeyedService<INotifier>(Channel.Email);
Console.WriteLine(email.Send("tyler.brooks@example.com", "Refund of $84.50 issued"));
// keys are compared with Equals: the string "Sms" is not Channel.Sms
Console.WriteLine($"Key \"Sms\" (string): {provider.GetKeyedService<INotifier>("Sms")?.GetType().Name ?? "null"}");
Console.WriteLine($"Key Channel.Sms: {provider.GetKeyedService<INotifier>(Channel.Sms)?.GetType().Name ?? "null"}");
public enum Channel { Sms, Email }
Output:
Email to tyler.brooks@example.com: Refund of $84.50 issued
Key "Sms" (string): null
Key Channel.Sms: SmsNotifier

The string "Sms" found nothing, while Channel.Sms found SmsNotifier. Keys are matched with Equals, not by name, so don’t mix the two styles in one app.
Pro Tip: [FromKeyedServices] needs a constant, and enum values work there too: [FromKeyedServices(Channel.Sms)].
[ServiceKey]: Read the Key Inside the Service
Sometimes one class serves several keys and needs to know which one it was created for. Mark a constructor parameter with [ServiceKey]:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddKeyedSingleton<INotifier, RegionalSms>("sms-east");
services.AddKeyedSingleton<INotifier, RegionalSms>("sms-west");
using var provider = services.BuildServiceProvider();
Console.WriteLine(provider.GetRequiredKeyedService<INotifier>("sms-east").Send("(617) 555-0112", "Pickup ready"));
Console.WriteLine(provider.GetRequiredKeyedService<INotifier>("sms-west").Send("(503) 555-0198", "Pickup ready"));
public class RegionalSms([ServiceKey] string key) : INotifier
{
public string Send(string to, string text) => $"[{key}] SMS to {to}: {text}";
}
Output:
[sms-east] SMS to (617) 555-0112: Pickup ready
[sms-west] SMS to (503) 555-0198: Pickup ready
One RegionalSms class, two registrations, and each instance got its own key, a bit like named settings in the options pattern.
GetKeyedServices: Several Registrations Under One Key
A key doesn’t have to be unique. Register two notifiers under order-shipped and ask for one, then for all:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddKeyedSingleton<INotifier, EmailNotifier>("order-shipped");
services.AddKeyedSingleton<INotifier, SmsNotifier>("order-shipped");
services.AddKeyedSingleton<INotifier, PushNotifier>("refund");
using var provider = services.BuildServiceProvider();
var one = provider.GetRequiredKeyedService<INotifier>("order-shipped");
Console.WriteLine($"GetRequiredKeyedService: {one.GetType().Name} (last one wins)");
foreach (var n in provider.GetKeyedServices<INotifier>("order-shipped"))
Console.WriteLine($"GetKeyedServices: {n.GetType().Name}");
Console.WriteLine($"Injected IEnumerable: {ActivatorUtilities.CreateInstance<ShippedAlerts>(provider).Count} notifiers");
Console.WriteLine($"GetServices (no key): {provider.GetServices<INotifier>().Count()} notifiers");
public class ShippedAlerts([FromKeyedServices("order-shipped")] IEnumerable<INotifier> all)
{
public int Count => all.Count();
}
Output:
GetRequiredKeyedService: SmsNotifier (last one wins)
GetKeyedServices: EmailNotifier
GetKeyedServices: SmsNotifier
Injected IEnumerable: 2 notifiers
GetServices (no key): 0 notifiers
The single-service call returns the last registration, just like plain DI. GetKeyedServices and the keyed IEnumerable parameter both got the two, while plain GetServices found zero.
KeyedService.AnyKey as a Fallback Key
KeyedService.AnyKey registers a fallback that matches every key without its own registration. The factory receives the key, so it can build a matching object:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddKeyedSingleton<INotifier>(KeyedService.AnyKey,
(sp, key) => new LogNotifier(key?.ToString() ?? "none"));
services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");
using var provider = services.BuildServiceProvider();
foreach (var key in new[] { "sms", "slack", "teams" })
Console.WriteLine(provider.GetRequiredKeyedService<INotifier>(key).Send("ops@example.com", "Disk 91% full"));
var named = provider.GetKeyedServices<INotifier>(KeyedService.AnyKey);
Console.WriteLine($"GetKeyedServices(AnyKey): {string.Join(", ", named.Select(n => n.GetType().Name))}");
try { provider.GetKeyedService<INotifier>(KeyedService.AnyKey); }
catch (InvalidOperationException ex) { Console.WriteLine($"GetKeyedService(AnyKey): {ex.Message}"); }
public class LogNotifier(string channel) : INotifier
{
public string Send(string to, string text) => $"[log:{channel}] {to}: {text}";
}
Output:
SMS to ops@example.com: Disk 91% full
[log:slack] ops@example.com: Disk 91% full
[log:teams] ops@example.com: Disk 91% full
GetKeyedServices(AnyKey): SmsNotifier
GetKeyedService(AnyKey): KeyedService.AnyKey cannot be used to resolve a single service.

sms still got its own notifier, while slack and teams fell back to LogNotifier. GetKeyedServices(KeyedService.AnyKey) listed only the services registered with a real key.
Important: on .NET 10, asking for one service with AnyKey throws: “KeyedService.AnyKey cannot be used to resolve a single service.” That’s a .NET 10 breaking change; .NET 8 and 9 behaved differently.
Keyed Services in Blazor with [Inject(Key = …)]
Razor components can’t use [FromKeyedServices] on a property, so Blazor (.NET 8 and later) adds a Key property to [Inject]. A component on the same notifiers looks like this:
@page "/order-status"
<p>@Notifier.Send("(512) 555-0147", "Order #4821 shipped")</p>
@code {
[Inject(Key = "sms")]
public INotifier Notifier { get; set; } = default!;
}
Keyed injection in Blazor components goes through this attribute, not the @inject directive, so the property sits in @code. Registration is the same AddKeyedScoped call in Program.cs.
Keyed HttpClient with AddAsKeyed (.NET 9+)
From .NET 9, a named HttpClient can become a keyed service. Call AddAsKeyed() on the builder and inject the client by its name. This one needs Microsoft.Extensions.Http 10.0.14 and calls the API above:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.Http@10.0.14
#:property PublishAot=false
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddHttpClient("notifyApi", c => c.BaseAddress = new Uri("http://localhost:5933/"))
.AddAsKeyed(); // HttpClient as a keyed scoped service
services.AddScoped<ShippingDesk>();
using var provider = services.BuildServiceProvider();
using var scope = provider.CreateScope();
var desk = scope.ServiceProvider.GetRequiredService<ShippingDesk>();
Console.WriteLine(await desk.TextCustomerAsync());
public class ShippingDesk([FromKeyedServices("notifyApi")] HttpClient http)
{
public Task<string> TextCustomerAsync() => http.GetStringAsync("notify/sms");
}
Output:
SMS to (512) 555-0147: Order #4821 shipped
ShippingDesk got a configured client with no IHttpClientFactory in sight. The default lifetime is Scoped, so resolve it from a scope, as I did here. My HttpClient vs IHttpClientFactory guide explains why handlers still rotate underneath.
Note: Microsoft’s docs warn against a Transient lifetime for keyed HttpClient instances, because the container captures the disposable client and handler.
What Happens When a Keyed Service Isn’t Registered?
Three ways to hit a missing key: GetRequiredKeyedService, a constructor asking for it, and the build-time check. I caught each in a try-catch block to print the real .NET 10 message:
#!/usr/bin/env dotnet
#:package Microsoft.Extensions.DependencyInjection@10.0.14
#:property PublishAot=false
#:include Notifiers.cs
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddKeyedSingleton<INotifier, SmsNotifier>("sms");
services.AddSingleton<OrderAlerts>();
using var provider = services.BuildServiceProvider();
try { provider.GetRequiredKeyedService<INotifier>("fax"); }
catch (InvalidOperationException ex) { Console.WriteLine($"1) {ex.Message}"); }
try { provider.GetRequiredService<OrderAlerts>(); }
catch (InvalidOperationException ex) { Console.WriteLine($"2) {ex.Message}"); }
try { services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true }); }
catch (AggregateException ex) { Console.WriteLine($"3) {ex.InnerExceptions[0].Message}"); }
public class OrderAlerts([FromKeyedServices("fax")] INotifier notifier)
{
public INotifier Notifier => notifier;
}
Output:
1) No keyed service for type 'INotifier' using key type 'System.String' has been registered.
2) Unable to resolve service for type 'INotifier' while attempting to activate 'OrderAlerts'.
3) Error while validating the service descriptor 'ServiceType: OrderAlerts Lifetime: Singleton ImplementationType: OrderAlerts': Unable to resolve service for type 'INotifier' while attempting to activate 'OrderAlerts'.

Message 1 names the key’s type but not its value, so log the key yourself. Message 2 doesn’t mention a key at all.
Message 3 is the one you want: ValidateOnBuild catches the bad key at startup. ASP.NET Core turns it on in Development, so a typo in [FromKeyedServices] fails before the first request.
Keep going with the rest of the ASP.NET Core setup:
- Add sign-in and roles with Blazor authentication
- Load appsettings per environment
- Global error handling in ASP.NET Core
- All ASP.NET Core tutorials
Frequently Asked Questions
Which .NET version added keyed services?
.NET 8, in Microsoft.Extensions.DependencyInjection 8.0. Keyed HttpClient through AddAsKeyed came in .NET 9. Everything in this post ran on .NET 10 with package version 10.0.14. The keyed services section on Microsoft Learn has the ASP.NET Core samples.
Can a keyed service key be something other than a string?
Yes. The key is an object, so enums, ints or records all work as long as Equals matches. A string and an enum with the same text are different keys.
What is the difference between GetKeyedService and GetRequiredKeyedService?
GetKeyedService returns null for a key with no registration. GetRequiredKeyedService throws an InvalidOperationException that says no keyed service is registered for that type and key type.
Can I use FromKeyedServices with a key that comes from the request?
No, attribute arguments must be constants. Inject IServiceProvider and call GetKeyedService with the route value, as the /notify/{channel} endpoint does.
How do I inject a keyed HttpClient?
Add .AddAsKeyed() after AddHttpClient("name") and inject [FromKeyedServices("name")] HttpClient. The keyed DI article for IHttpClientFactory covers lifetimes and the global opt-in.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…