Search code examples
c#inheritancedependency-injectionninjectabstract-class

Ninject: GetAll instances that inherit from the same abstract class


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.


Solution

  • instead of creating two bindings, the second one with a "redirect" to the first, what you can also do is:

    _kernel.Bind<MyAbstractClass, MyDerivedClass1>()
           .To<MyDerivedClass1>().InSingletonScope();
    _kernel.Bind<MyAbstractClass, MyDerivedClass2>()
           .To<MyDerivedClass1>().InSingletonScope();
    

    This expresses the intention more clearly.