Introduction
Dependency injection plays a crucial role in every programming language.
Microsoft has introduced many new features and significant enhancements in .Net 8. “Keyed Services” is one of the important, powerful enhancements in the dependency injection shipped with .Net Core 8.
In this article, we will explore Keyed Services .Net 8, illustrating with an example. This article is suitable for beginners, intermediate learners, and professionals.
We are going to cover the following in this article.
- How do you deal with multiple implementations of the interface prior to Keyed Services?
- Introduction of Keyed Services?
- Lifetime scope for Keyed Services.
- AddKeyedSingleton
- AddKeyedScoped
- AddKeyedTransient
- How to register and resolve dependencies using Keyed Services
Prerequisites
Below are the prerequisites for Keyed Services.
- .NET 8 SDK (RC1 or later version)
- Visual Studio 2022 version 17.8 or later
Let’s start with the use case of the Keyed Services.
How do you deal with multiple implementations of the interface prior to Keyed Services?
Let’s assume that we want to implement report generator functionality, which can generate reports on XML, CSV, and PDF as per the user's preference.
Now, think how you will implement this prior to .NET 8. Let’s create a demo MVC core project in .NET Core 6.0.
Step 1. Create a .NET Core MVC project using .NET Core 6.0.
Step 2. Create an Interface called “IReportGenerator”.