Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyed dependency injection in ASP.NET Core

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");
like image 775
TheDoomDestroyer Avatar asked Sep 06 '25 03:09

TheDoomDestroyer


2 Answers

Microsoft has added keyed dependencies starting with .NET 8, see the doc:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-8.0#keyed-services

like image 182
dusky Avatar answered Sep 07 '25 22:09

dusky


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

like image 35
Nkosi Avatar answered Sep 07 '25 22:09

Nkosi