.net-coredependency-injection

.NET Core keyed dependency injection


Unity, Autofac and probably quite a few other Dependency injection packages all support "keyed dependency injection containers" that allow to register multiple implementations of an interface and identify them uniquely via a key (be it a string, an int, an enum or whatever else).

However, .NET Core, so far I can see at least, doesn't have such a feature and if I were to try to implement anything like this, I'd have to do a workaround or find some hacky solutions for it. I am wondering, is there a particular reason this has not been introduced in .NET Core?

Unity example:

     container.RegisterType<IService, ServiceImplementation1>("1");
     container.RegisterType<IService, ServiceImplementation2>("2");

Autofac example:

     builder.RegisterType<ServiceImplementation1>().Keyed<IService>("1");
     builder.RegisterType<ServiceImplementation2>().Keyed<IService>("2");

Solution

  • ...,is there a particular reason this has not been introduced in .NET Core?

    Short answer: Yes

    Reference Default service container replacement

    The built-in service container is designed to serve the needs of the framework and most consumer apps. We recommend using the built-in container unless you need a specific feature that the built-in container doesn't support, such as:

    • Property injection
    • Injection based on name (a.k.a keyed)
    • Child containers
    • Custom lifetime management
    • Func support for lazy initialization
    • Convention-based registration

    note: emphasis mine