【问题标题】:Extending Ninject bindings via conventions通过约定扩展 Ninject 绑定
【发布时间】:2012-12-11 14:29:39
【问题描述】:

我通过模块在我的应用程序中手动设置了 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

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

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

问候,

多米尼克

【问题讨论】:

    标签: .net ninject


    【解决方案1】:

    您可以使用约定。例如

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

    【讨论】:

    • 是的,这适用于初始注册。实际情况有点棘手,因为有人在创建第一个绑定后尝试添加额外的绑定(到 IBootstrapable)。但我认为这并没有得到真正的支持。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多