.NET keyed service

Content:

I saw it mentioned on LinkedIn. As a new feature in DI in recent .NET versions.

It is esy to implement:

using System;

using Microsoft.Extensions.DependencyInjection;

namespace KeyedDI
{
    public interface IDemo
    {
        void Show();
    }
    public class DemoImpl : IDemo
    {
        public void Show()
        {
            Console.WriteLine("DemoImpl");
        }
    }
    public enum AB { A, B }
    public class DemoImplA : IDemo
    {
        public void Show()
        {
            Console.WriteLine("DemoImplA");
        }
    }
    public class DemoImplB : IDemo
    {
        public void Show()
        {
            Console.WriteLine("DemoImplB");
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            IServiceCollection coll = new ServiceCollection();
            coll.AddSingleton<IDemo>(s => new DemoImpl());
            coll.AddKeyedSingleton<IDemo>(AB.A, (s,k) => new DemoImplA());
            coll.AddKeyedSingleton<IDemo>(AB.B, (s,k) => new DemoImplB());
            IServiceProvider cont = coll.BuildServiceProvider();
            IDemo o = cont.GetRequiredService<IDemo>();
            o.Show();
            IDemo oa = cont.GetRequiredKeyedService<IDemo>(AB.A);
            oa.Show();
            IDemo ob = cont.GetRequiredKeyedService<IDemo>(AB.B);
            ob.Show();
        }
    }
}

But I don't see the point. The traditional way is to initialize with a hardcoded class. The DI way is to initialize with whatever has been configued implementing that interface. Now we initialize using DI but specifying what class using hardcoded identifier. Why not just use the traditional way??

Comments: