Keyed Dependency Injection (Keyed Services) in DotNet Core 8.0

Keyed Dependency Injection is one of the best and most useful feature and it has been added in DotNet Core 8.0

Keyed Dependency Injection is used to inject dependency where multiple classes are implementing the same Interface and you want to use these different implementations in your dot net application.

What’s the need of using Keyed Dependency Injection?

Let’s say I have following interface.

public interface IEmployeeRepository
{
    string EmployeeName();
}

And two different classes are implementing the same interface.

public class EmployeeRepository1 : IEmployeeRepository
{
    public string EmployeeName() => "Hello From Employee Repository 1";
}

public class EmployeeRepository2 : IEmployeeRepository
{
    public string EmployeeName() => "Hello From Employee Repository 2";
}

Now I want to register the dependency for both the classes then so far it was not possible in dot net core. But now this is possible using keyed dependency injection with the release of dot net core 8.0.

How to register Keyed Dependency Injection in Asp.Net Core?

Here are the steps to use Keyed Dependency Injection in Asp.Net Core Web API application.

This concept is applicable in other dot net core frameworks too.

Lets start by registering the service in Program.cs class.

builder.Services.AddKeyedSingleton<IEmployeeRepository, EmployeeRepository1>("employee1");
builder.Services.AddKeyedSingleton<IEmployeeRepository, EmployeeRepository2>("employee2");

You can use any of the following method to register the dependency.

  • AddKeyedSingleton
  • AddKeyedScoped
  • AddKeyedTransient

Make sure to use a unique key while registering your services in DI container.

You can also watch this video to learn about the Keyed Dependency Injection in DotNet Core.

Keyed Dependency Injection

How to resolve the Keyed Dependency Injection in Asp.Net Core Controller?

You can resolve the keyed dependency using FromKeyedServices parameter.

Example: Resolving dependency using Controller Constructor.

[Route("api/[controller]")]
[ApiController]
public class EmployeeController(
    [FromKeyedServices("employee1")] IEmployeeRepository employee1,
    [FromKeyedServices("employee2")] IEmployeeRepository employee2
    ) : ControllerBase
{
    [HttpGet("")]
    public IActionResult EmployeeName() => Ok(employee1.EmployeeName() +" "+ employee2.EmployeeName());
}

You can also resolve the dependency directly in the method.

[Route("api/[controller]")]
[ApiController]
public class EmployeeController() : ControllerBase
{
    [HttpGet("")]
    public IActionResult EmployeeName(
        [FromKeyedServices("employee1")] IEmployeeRepository employee1,
        [FromKeyedServices("employee2")] IEmployeeRepository employee2
        ) => Ok(employee1.EmployeeName() +" "+employee2.EmployeeName());
}

That’s it. Just run the application and share the output in the comment section below.