How to Inject a Keyed Service with [FromKeyedServices] in .NET C#
When one interface has two implementations, .NET's service container can keep both, each under its own key. Register them with AddKeyedSingleton, ask for one by its key with GetRequiredKeyedService, or put [FromKeyedServices] on a constructor parameter and let the container pass the right one.
Syntax
// Register each implementation under its own key
services.AddKeyedSingleton<TService, TImplementation>(<key>);
// Ask the provider for the one registered under a key
TService <service> = provider.GetRequiredKeyedService<TService>(<key>);
// Or let the container pass it to a constructor parameter
class <Consumer>([FromKeyedServices(<key>)] TService <parameter>)
| Part | What to put there |
|---|---|
services | The IServiceCollection you register services in |
TService | The type the rest of the code asks for, usually an interface |
TImplementation | The class the container creates for this key |
<key> | The key that tells the registrations apart. This guide uses strings |
provider | The service container, built from services |
<service> | The variable that receives the service |
<Consumer>, <parameter> | A class the container creates, and the constructor parameter that receives the keyed service |
The two methods and the attribute are in the Microsoft.Extensions.DependencyInjection namespace. The .NET API reference describes the attribute in one sentence: Indicates that the parameter should be bound using the keyed service registered with the specified key. AddKeyedScoped and AddKeyedTransient register keyed services with the other two lifetimes, and take the key the same way.
The Example
A console app called KeyedGreeters has one interface, IGreeter, and two classes that implement it: FormalGreeter says good morning, and CasualGreeter says hey. Both are registered, each under its own key. The app asks the container for the formal one by its key, and a WelcomeDesk class gets the casual one through [FromKeyedServices].
Prerequisites
- The .NET 10 SDK.
dotnet --versionprints a version that starts with10.0; this guide used 10.0.404.
Step 1: Create the App
In a terminal, in the folder where you keep your projects, create a console app, move into it and add the dependency injection package:
dotnet new console -o KeyedGreeters
cd KeyedGreeters
dotnet add package Microsoft.Extensions.DependencyInjection --version 10.0.15
dotnet new console -o KeyedGreeterscreates a console app in a newKeyedGreetersfolder.cd KeyedGreetersmoves into it.dotnet add packageadds Microsoft.Extensions.DependencyInjection, the package with .NET's service container, to the project.--versionkeeps you on the version this guide used.
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/KeyedGreeters/KeyedGreeters.csproj:
Restore succeeded.
…
info : PackageReference for package 'Microsoft.Extensions.DependencyInjection' version '10.0.15' added to file '/Users/you/source/KeyedGreeters/KeyedGreeters.csproj'.
info : Writing assets file to disk. Path: /Users/you/source/KeyedGreeters/obj/project.assets.json
log : Restored /Users/you/source/KeyedGreeters/KeyedGreeters.csproj (in 997 ms).
Open the KeyedGreeters folder in VS Code, or KeyedGreeters.csproj in Visual Studio.
Step 2: Write One Interface with Two Implementations
Replace everything in Program.cs with an interface and two classes that implement it:
interface IGreeter
{
string Greet(string name);
}
class FormalGreeter : IGreeter
{
public string Greet(string name) => $"Good morning, {name}.";
}
class CasualGreeter : IGreeter
{
public string Greet(string name) => $"Hey {name}!";
}
IGreeter is what the rest of the code asks for. FormalGreeter and CasualGreeter both implement it, so a request for an IGreeter could mean either one. The keys in the next step say which.
Step 3: Register Each One Under Its Own Key
Add these lines at the top of Program.cs, above interface IGreeter:
using Microsoft.Extensions.DependencyInjection;
ServiceCollection services = new();
// Two implementations of the same interface, each registered under its own key.
services.AddKeyedSingleton<IGreeter, FormalGreeter>("formal");
services.AddKeyedSingleton<IGreeter, CasualGreeter>("casual");
using ServiceProvider provider = services.BuildServiceProvider();
ServiceCollectionholds the registrations: which class to create when the code asks for a type.AddKeyedSingleton<IGreeter, FormalGreeter>("formal")registersFormalGreeteras anIGreeterunder the key"formal", and the next line registersCasualGreeterunder"casual". Singleton is the lifetime, the one Microsoft's documentation describes as a service that isn't disposed until the app shuts down.BuildServiceProvider()turns the registrations into the service container,provider, which creates the services when they're asked for.usingdisposes it when the program ends.
Step 4: Ask for a Service by Its Key
Add these lines below using ServiceProvider provider = services.BuildServiceProvider();:
// Ask for one by its key.
IGreeter formal = provider.GetRequiredKeyedService<IGreeter>("formal");
Console.WriteLine(formal.Greet("Ana"));
GetRequiredKeyedService<IGreeter>("formal") returns the IGreeter registered under "formal", which is a FormalGreeter. Its documentation lists an InvalidOperationException for when there's no such service, so a key that nothing is registered under fails right here. GetKeyedService<IGreeter> is the same lookup, but it returns null instead of throwing.
Step 5: Let the Container Pass One to a Constructor
Add a class whose constructor wants the casual greeter, at the end of Program.cs:
class WelcomeDesk([FromKeyedServices("casual")] IGreeter greeter)
{
public string Welcome(string name) => greeter.Greet(name);
}
- The parameter list after
WelcomeDeskis the class's constructor, a primary constructor, sogreetercan be used anywhere in the class. [FromKeyedServices("casual")]on the parameter tells the container whichIGreeterto pass: the one registered under"casual".
Register WelcomeDesk too, below the two keyed registrations:
services.AddSingleton<WelcomeDesk>();
And ask for it, below Console.WriteLine(formal.Greet("Ana"));:
// Or let the container hand it to a constructor, chosen by [FromKeyedServices].
WelcomeDesk desk = provider.GetRequiredService<WelcomeDesk>();
Console.WriteLine(desk.Welcome("Ben"));
WelcomeDesk itself has no key, so GetRequiredService<WelcomeDesk>() asks for it the plain way. To create it, the container reads the attribute on the constructor's parameter and passes the greeter registered under "casual".
Step 6: Run It
dotnet run
Good morning, Ana.
Hey Ben!

The first line came from FormalGreeter, which the app asked for by its key. The second came from CasualGreeter: the app never named it, and the container passed it to WelcomeDesk because of the attribute on its constructor.
The Complete File
using Microsoft.Extensions.DependencyInjection;
ServiceCollection services = new();
// Two implementations of the same interface, each registered under its own key.
services.AddKeyedSingleton<IGreeter, FormalGreeter>("formal");
services.AddKeyedSingleton<IGreeter, CasualGreeter>("casual");
services.AddSingleton<WelcomeDesk>();
using ServiceProvider provider = services.BuildServiceProvider();
// Ask for one by its key.
IGreeter formal = provider.GetRequiredKeyedService<IGreeter>("formal");
Console.WriteLine(formal.Greet("Ana"));
// Or let the container hand it to a constructor, chosen by [FromKeyedServices].
WelcomeDesk desk = provider.GetRequiredService<WelcomeDesk>();
Console.WriteLine(desk.Welcome("Ben"));
interface IGreeter
{
string Greet(string name);
}
class FormalGreeter : IGreeter
{
public string Greet(string name) => $"Good morning, {name}.";
}
class CasualGreeter : IGreeter
{
public string Greet(string name) => $"Hey {name}!";
}
class WelcomeDesk([FromKeyedServices("casual")] IGreeter greeter)
{
public string Welcome(string name) => greeter.Greet(name);
}

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| A key spelled differently from its registration | GetRequiredKeyedService throws InvalidOperationException, because nothing is registered under that key | Keep each key in one place, such as a constant |
Using GetKeyedService for a service that must exist | It returns null when nothing is registered under the key | Use GetRequiredKeyedService, which throws instead |
Not registering the class that has the [FromKeyedServices] parameter | GetRequiredService throws InvalidOperationException, because there's no such service | Register it, as services.AddSingleton<WelcomeDesk>() does |
Creating the class yourself with new | The container isn't involved, so the attribute does nothing: you pass the greeter yourself | Ask the container for the class |
FAQ
Does the key have to be a string?
No. Microsoft's documentation says The key can be any object you want, as long as the type correctly implements Equals.
Why not ask the provider everywhere?
Microsoft's guidance is to avoid that pattern, the service locator: don't invoke GetService to obtain a service instance when you can use DI instead. The attribute keeps constructor injection possible when the service a class needs has a key.
Does it work in ASP.NET Core?
Yes. Microsoft's ASP.NET Core documentation shows [FromKeyedServices] on the parameters of minimal API endpoints, on a SignalR hub's primary constructor, and in middleware.
Conclusion
Keyed services let one interface have several registered implementations, told apart by a key. Register each with AddKeyedSingleton, ask for one with GetRequiredKeyedService, or put [FromKeyedServices] on a constructor parameter and let the container pass it. In the example, the same IGreeter interface gave Good morning, Ana. by its key, and Hey Ben! through WelcomeDesk.
Additional Resources
- Dependency injection in .NET: Keyed services — registering services under keys and injecting them with the attribute.
- FromKeyedServicesAttribute — the attribute, its constructors and its
Keyproperty. - ServiceProviderKeyedServiceExtensions.GetRequiredKeyedService — the lookup by key, and the exception when nothing is registered.
- Dependency injection in ASP.NET Core: Keyed services — the attribute in minimal API endpoints, SignalR hubs and middleware.
