Ninject:从相同抽象类继承的GetAll实例 [英] Ninject: GetAll instances that inherit from the same abstract class

查看:88
本文介绍了Ninject:从相同抽象类继承的GetAll实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ninject是否有可能获得从特定抽象类继承的所有实例?例如,我有以下抽象类.

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>();

是否有一种方法可以获取所有继承自MyAbstractClass的类?我尝试了以下方法,但均未成功.

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>();

希望上面的GetAll()方法将返回两个实例的列表,一个实例是MyDerivedClass1,第二个实例是MyDerivedClass2.

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.

推荐答案

而不是创建两个绑定,第二个绑定具有重定向"到第一个绑定,您还可以执行以下操作:

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.

这篇关于Ninject:从相同抽象类继承的GetAll实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆