Understanding Dependency Injection (Recap)
Difference b/w Singleton, Scoped, and Transient in DI
Keyed Services in .NET 8
How to achieve the same in older versions of .NET
If you are unaware of the concept of Dependency Injection read this article :
EP 62: Dependency Injection Explained in .NET
Many people struggle to understand the difference between the scope of dependencies. I have created a detailed video with a demo code of .NET API to explain the difference between Singleton, Scoped, and Transient :
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 :
There are a couple of ways to inject the keyed services
Controller level & assign them
Method level specifically
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 :
Whenever you’re ready, there are 2 ways I can help you:
Promote yourself to 10400+ subscribers by sponsoring this newsletter
Patreon Community: Join and gain access to the 200+ articles I have published so far in one place. Join here