[英]How can i find one derived class implementation when i have IEnumerable<T> from Ninject binding
我有一个将接口成员实现为抽象方法的基类。 有一些派生类可以重写此抽象方法。 我有Ninject DI,内核将给出T(IEnumerable<T>)
的数组。 我如何使用此IEnumerable<T>
调用一个特定的派生类实现。
这是一些示例代码
这是我的界面
public interface ICreateBatch
{
int CreateBatch();
}
这是我与接口实现的基类
public abstract class CreateBatchBase:ICreateBatch
{
public abstract int CreateBatch();
}
这是派生类的实现之一
public class CreateDerived1Batch:CreateBatchBase
{
public override int CreateBatch()
{
//Derived one implementation
}
}
public class CreateDerived2Batch:CreateBatchBase
{
public override int CreateBatch()
{
//Derived two implementation
}
}
Ninject给了我IEnumerable。 如何从CreateDerived1Batch专门调用CreateBatch()?
提前致谢。
我认为这种情况下的正常方法是使用上下文绑定(请参阅https://github.com/ninject/Ninject/wiki/Contextual-Binding )。 例如,如果您像这样绑定接口:
kernel.Bind<ICreateBatch>().To<CreateDerived1Batch>().WhenInjectedInto(typeof(TypeDependingOn1);
kernel.Bind<ICreateBatch>().To<CreateDerived2Batch>().WhenInjectedInto(typeof(TypeDependingOn2);
正确的ICreateBatch
应该分别注入TypeDependingOn1
和TypeDependingOn2
。
您可以使用LINQ扩展方法OfType<T>
来仅过滤给定类型的项目:
collection.OfType<Derived>().Method();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.