Keyed Service Dependency Injection in .NET

If you are unaware of the concept of Dependency Injection read this article :

EP 62: Dependency Injection Explained in .NET

Keyed Services in .NET 8

Keyed service retrieves the dependency using a key when an interface simply has multiple implementations. This concept was introduced in .NET 8.

Suppose we have the following piece of code where we have two classes implementing the same interface :

public interface IPrinter
{
    void Print(string message);
}

internal class ConsolePrinter : IPrinter
{
    public void Print(string message)
    {
        Console.WriteLine(message);
    }
}

internal class FilePrinter : IPrinter
{
    public void Print(string message)
    {
        File.WriteAllText("file.txt", message);
    }
}

Keyed Services in .NET 8

As we can see from the previous code snippet, the two classes are implementing a single interface, let’s see how can we register its dependency using a key.

We need to provide a string-based key in the Program.cs, but we can use enums as well instead of hard coding string values :

Keyed Service Dependency Injection in .NET

There are a couple of ways to inject the keyed services

  • Controller level & assign them

  • Method level specifically

Keyed Service Dependency Injection in .NET

Currently, we have a limitation that this can not be applied directly to Minimal APIs yet.

How to achieve the same behavior in older versions of .NET?

We can achieve the same in older versions as well like this :

Keyed Service Dependency Injection in .NET

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place