.NET 8 Keyed Services in Dependency Injection

Introduction

.NET 8 Introduced Keyed Services in DI (Dependency Injection).

This feature allows the registration of multiple implementations of the same Interface within DI using a key.

The below methods are used for registering in Program.cs.

  • AddKeyedSingleton
  • AddKeyedScoped
  • AddKeyedTransient

Example

1. Defining Interface

//ISample.cs

using System;
namespace KeyedServices.Abstract
{
    public interface ISample
    {
        public void Display();
    }
}

2. Defining classes

//Sample1.cs

using KeyedServices.Abstract;

namespace KeyedServices
{
    public class Sample1 : ISample
    {
        public Sample1()
        {
        }

        public void Display()
        {
            Console.WriteLine("Display from Sample 1");
        }
    }
}
// Sample2.cs

using KeyedServices.Abstract;

namespace KeyedServices
{
    public class Sample2 : ISample
    {
        public Sample2()
        {
        }

        public void Display()
        {
            Console.WriteLine("Display from Sample 2");
        }
    }
}

3. Registering Dependecies and Calling - Program.cs

using KeyedServices;
using KeyedServices.Abstract;
using Microsoft.Extensions.DependencyInjection;

public class Program
{
    // Program.cs
    public static void Main(string[] args)
    {

        var serviceProvider = new ServiceCollection()
                    .AddKeyedSingleton<ISample>("Sample1", new Sample1())
                    .AddKeyedSingleton<ISample>("Sample2", new Sample2())
                    .BuildServiceProvider();

        var sample1 = serviceProvider.GetKeyedService<ISample>("Sample1");

        var sample2 = serviceProvider.GetKeyedService<ISample>("Sample2");

        // Calling Sample 1 instance.
        sample1.Display();

        // Calling Sample 2 instance.
        sample2.Display();

        Console.ReadLine();
    }
}

4. Result

Output image

Conclusion

keyed Services provide a valuable addition to the DI system. This provides a flexible approach to dependency injection.

Github Link: Keyed-Services (github.com)


Similar Articles