0

Is there a way in the native .NET Core DI Container to use named bindings like in Ninject?

For example if I have two implementations of the same interface and I want them in different scenarios.

Expecting to register them like:

services.AddSingleton<FirstValidationRule, IValidationRule>("first");
services.AddSingleton<SecondValidationRule, IValidationRule>("second");

And later to call the desired service (for example the second one) like:

IValidationRule chosenService = provider.GetService<IValidationRule>("second");
gneric
  • 3,457
  • 1
  • 17
  • 30
  • 2
    Using the DI container like this is actually an *anti*-pattern. In order to request a service by name you'd need access to the provider or services collection. Why not pass injec a *factory function* instead that will pick the correct instance based on a name? That's what the factory pattern is about. You can create an IRuleFactory interface, or you can try to actuall register a `Func` function. – Panagiotis Kanavos Mar 20 '18 at 10:42
  • @PanagiotisKanavos In this case inside the factory I will instantiate every ValidationRule with new keyword, and eventually if they have constructor parameters with each one having other parameters I can use provider.GetService get every parameter of the ValidationRule individually ? Am I on right track ? – gneric Mar 20 '18 at 10:46
  • That said, using named registrations *does* make sense during configuration, or when you want to create the root object of your graph. Saying `var process=provider.GetService(processName); process.Run(input);` makes more sense than requesting rules by name *inside* the business process object itself. Unfortunately, this isn't available out of the box – Panagiotis Kanavos Mar 20 '18 at 10:46
  • 1
    @gneric you don't need to do that. The method could return the registered instances of FirstValidationRule, SecondValidationRule etc based on a name. It could be something as simple as looking up the name in a string-to-type dictionary. – Panagiotis Kanavos Mar 20 '18 at 10:47

0 Answers0