通过约定扩展 Ninject 绑定



>我通过模块在我的应用程序中手动设置 Ninject (v3) 绑定:

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

重要的是,我实际上扩展了现有的绑定(因此保留了单格尔顿范围。

这可以通过扩展点以某种方式完成吗?

问候

多米尼克

您可以使用约定。

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

最新更新