2012-12-11 96 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)。但我認爲這不是真的支持。 –