Ninject: GetAll instances that inherit from the sa

2019-08-26 14:45发布

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.

2条回答
放荡不羁爱自由
2楼-- · 2019-08-26 14:53

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:

_kernel = new StandardKernel();
_kernel.Bind<MyAbstractClass>().To<MyDerivedClass1>().InSingletonScope();
_kernel.Bind<MyAbstractClass>().To<MyDerivedClass2>().InSingletonScope();

//returns both
var allImplementations = _kernel.GetAll<MyAbstractClass>();

EDIT: Multiple bindings to singleton.

_kernel = new StandardKernel();
_kernel.Bind<MyDerivedClass1>().ToSelf().InSingletonScope();
_kernel.Bind<MyDerivedClass2>().ToSelf().InSingletonScope();

_kernel.Bind<MyAbstractClass>().ToMethod(x => _kernel.Get<MyDerivedClass1>());
_kernel.Bind<MyAbstractClass>().ToMethod(x => _kernel.Get<MyDerivedClass2>());
查看更多
唯我独甜
3楼-- · 2019-08-26 15:17

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.

查看更多
登录 后发表回答