3

In .NET framework, you can use Ninject to achieve contextual binding.

So for example:

Bind<IWarrior>().To<Samurai>().WhenInjectedInto(typeof(OnLandAttack));
Bind<IWarrior>().To<SpecialNinja>().WhenInjectedInto(typeof(AmphibiousAttack));

This means you can inject different concrete implementations depending on what you're injecting into.

I cannot see any method to achieve the same thing in .NET Core 2.2 - is this not possible, or does it just require a bunch of extra configuration?

Example code from the Ninject site

ib4nez
  • 105
  • 7
  • What do you mean when you say you can't see the method? You took the code above from the docs, does it not work? – DavidG Mar 24 '19 at 18:14
  • 1
    I was under the impression this was unavailable in .NET Core @DavidG – ib4nez Mar 24 '19 at 18:20
  • There is no such feature in MS.DI. – Steven Mar 24 '19 at 18:53
  • 1
    See this [so answer](https://stackoverflow.com/questions/46693305/how-to-integrate-ninject-into-asp-net-core-2-0-web-applications/46747913) – Kalten Mar 24 '19 at 22:30
  • `Microsoft.Extensions.DependencyInjection` does not technically support contextual binding, though you can do this is a somewhat limited way via the factory overloads, i.e. you can provide a lamba "factory" as the service registration, and inside that lambda make determinations about what actual instance to return. If you need something more robust than that, then you will need to use an alternate DI container such as Autofac. See: https://github.com/aspnet/Extensions/tree/master/src/DependencyInjection. Ninject, it should be noted, is not currently supported, though. – Chris Pratt Mar 25 '19 at 16:44

1 Answers1

0

I had a need for something like this and ended up creating a NuGet package for it: https://www.nuget.org/packages/ServiceProviderContextualBinding/

Usage looks like this:

services.AddSingleton<IService, DefaultService>();
services.AddSingleton<ReplacementService>();
services.WithReplacement<IService, ReplacementService>()
    .AddSingleton<Consumer>();

This package is basically a facade over the ActivatorUtilities.CreateInstance method, which is part of the MS DI code.

Jack A.
  • 4,245
  • 1
  • 20
  • 34