Get different object from Ninject depending on ConstructorArgument

162 Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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)