3

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");
3

3 Answers 3

8

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

5

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

1
  • 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. Commented Apr 9, 2020 at 6:28
3

.NET 8 already added support for keyed services.

To register a keyed service, use one of the AddKeyedSingleton(), AddKeyedScoped(), or AddKeyedTransient() overloads, and provide an object as a key.

For example, you can register different implementations of an interface like this:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddKeyedSingleton<IService, ServiceImplementation1>("one");
builder.Services.AddKeyedSingleton<IService, ServiceImplementation2>("two");

//----------------------------------
// How to resolve services
public class TestService([FromKeyedServices("one")] IService service)
{
  // some stuff
}
1
  • Labelling it "already" four years after the question was asked is perhaps a bit odd. Commented Nov 17, 2024 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.