Keyed services for ASP.NET Core dependency injection example

Keyed services is a feature released in .NET 8 for dependency injection in ASP.NET Core.

It allows for adding multiple implementations of the same service to the IoC container with each implementation having a key identifier.

C# coding challenges

C# coding challenges

Our online code editor allows you to compile the answer.

This code example demonstrates how to add multiple implementations to the same service prior to .NET 8 using an IEnumerable.

It also shows how to add keyed services in .NET 8 for Minimal APIs as well as MVC and Web API endpoints.

Software

As .NET 8 is currently in preview, you'll need the preview version of Visual Studio 2022 (version 17.8 preview) and .NET 8 SDK (RC 1 or above).

.NET 8 is due to be released in November 2023. When it is released, you'll need to update Visual Studio 2022 to version 17.8 and ensure that the .NET 8 SDK is installed.

Get the application working

These are the steps to get the application working.

  • Fill out the code example form. We will send you an email where you can download the code example.

You are now ready to go.

Open the project in Visual Studio

Open up RoundTheCode.KeyedServices.sln in Visual Studio 2022 Preview.

Start the project in Visual Studio.

A browser should load up the application automatically. If it doesn't, hit https://localhost:8002, and test out the endpoints.

The Swagger endpoints

When you hit https://localhost:8002, it will load the Swagger documentation. Here are the endpoints:

  • /api/minimal-api - Using keyed services in .NET 8 using Minimal APIs.
  • /api/web-api/dotnet-7 - Using the IEnumerable type to get a list of implementations of the same service used prior to .NET 8.
  • /api/web-api/dotnet-8 - Using keyed services in a MVC/Web API endpoint using the FromKeyedService attribute.
  • /api/web-api/dotnet-8 - Using keyed services in a MVC/Web API endpoint using the IServiceProvider instance.

More information

Watch our video where we go ahead and talk through keyed services and how they work.

In addition, you can read more about keyed services in .NET 8 with our tutorial.