2012-12-11 116 views
1

我手动设置通过模块中我的应用程序Ninject(V3)绑定:扩展通过约定Ninject绑定

public class FooBarModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Kernel.Bind<IFooBar>().To<FooBarOne>().InSingletonScope(); 
     Kernel.Bind<IFooBar>().To<FooBarTwo>().InSingletonScope(); 
    } 
} 

现在,在我的系统中的一些类实现接口IBoostrapable

public class FooBarOne : IFooBar, IBootstrapable 
{ ... } 

我想自动扩展实现这个接口的类的Ninject绑定。

所以,最终我想能够做到:

var fooBars = Kernel.GetAll<IFooBar>(); 
var bootstrapbables = Kernel.GetAll<IBootstrapable>(); 
fooBars.Count().Should().Be(2); // Instance of FooBarOne and FooBarTwo 
bootstrapbables.Count().Should().Be(1); // instance of FooBarOne 

重要的是,我实际上是扩展了现有的绑定(所以保持singelton范围

可以这样。与扩展点莫名其妙地做了什么?

问候,

多米尼克

回答

2

您可以使用约定。例如。

kernel.Bind(x => x 
    .FromThisAssembly() 
    .SelectAllClasses() 
    .InheritedFrom<IFooBar>() 
    .BindAllInterfaces() 
    .Configure(c => c.InSingletonScope()); 
+0

是的,这适用于初始注册。实际案例有点棘手,因为有人在创建第一个绑定后尝试添加其他绑定(对IBootstrapable)。但我认为这不是真的支持。 –