Search code examples
c#dependency-injectionninjectninject-2

Get different object from Ninject depending on ConstructorArgument


I have following code:

kernel.Get<IFoo>(new ConstructorArgument("rule", myRule))

I want that I get different objects depending of the value in myRule. How do I do that? Something like this psedocode

Bind<IFoo>().To<Foo1>().When(x=>x.Parameters[0].Value.Type=="type1")
Bind<IFoo>().To<Foo2>().When(x=>x.Parameters[0].Value.Type=="type2")

where Type is a member of myRule


Solution

  • Accessing the type of constructor arguments is not easily possible. You might want to change to using either Named bindings or metadata and constraints instead.

    Bind<IFoo>().To<Foo1>().WithMetadata("Type", typeof(MyRule1))
    kernel.Get<IFoo>(m => m.Get<Type>("Type", null) == typeof(myRule), ConstructorArgument("rule", myRule))
    

    But remind to access the kernel only from the configuration (e.g. factories belonging to the configuration)