Is it possible for Ninject to get all instances that inherit from a specific Abstract Class? For example, I have the following Abstract Class.
public abstract class MyAbstractClass { }
Then I have the following two derived classes that both inherit from the same abstract class.
public class MyDerivedClass1 : MyAbstractClass { }
public class MyDerivedClass2 : MyAbstractClass { }
Now I am going to bind both derived classes with the Kernel because I want them to be in singleton scope.
_kernel = new StandardKernel();
_kernel.Bind<MyDerivedClass1>().ToSelf().InSingletonScope();
_kernel.Bind<MyDerivedClass2>().ToSelf().InSingletonScope();
I know the Kernel can return me an instance like the following.
_kernel.Get<MyDerivedClass1>();
Is there a way to get all of the classes that inherit from MyAbstractClass? I tried the following without success.
IEnumerable<MyAbstractClass> items = kernel.GetAll<MyAbstractClass>();
The hope was that the above GetAll() method would return a list of two instances, one would be MyDerivedClass1 and the second would be MyDerivedClass2.
Currently you're binding only to the implementation type, not the base class type, with
ToSelf
. It's effectively calling_kernel.Bind<MyDerivedClass1>().To<MyDerivedClass1>()
To bind the implementation types to the base type use:
EDIT: Multiple bindings to singleton.
instead of creating two bindings, the second one with a "redirect" to the first, what you can also do is:
This expresses the intention more clearly.