1

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");
TheDoomDestroyer
  • 2,434
  • 4
  • 24
  • 45
  • Does this answer your question? [How to register multiple implementations of the same interface in Asp.Net Core?](https://stackoverflow.com/questions/39174989/how-to-register-multiple-implementations-of-the-same-interface-in-asp-net-core) – Martin Mar 30 '20 at 19:36
  • [Maybe one of these hacky workarounds ... or helpful?](https://stackoverflow.com/questions/39174989/how-to-register-multiple-implementations-of-the-same-interface-in-asp-net-core) – Martin Mar 30 '20 at 19:37
  • As I was saying, I am well aware of the workarounds, but I wasn't sure why this feature isn't natively implemented in .NET Core's DI container. – TheDoomDestroyer Mar 31 '20 at 06:46

1 Answers1

4

...,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

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Microsoft's documentation doesn't really explain **why** it doesn't feature keyed DI, but oh well. I'll mark your answer as the correct one anyway. – TheDoomDestroyer Apr 09 '20 at 06:28