【问题标题】:Ninject Contextual Binding at RunTime运行时的 Ninject 上下文绑定
【发布时间】:2011-05-29 20:27:37
【问题描述】:

我正在尝试了解 Ninject 上下文绑定。我了解在设计时了解我的上下文的场景。例如我知道,当我想在测试类中使用它时,我可以使用命名属性将 DB 对象绑定到一个模拟数据库,当我从我的实际代码中使用它时,我可以使用它绑定到一个 SQL 数据库。

但是,我不知道如何在运行时处理上下文绑定。例如假设我正在为购物中心编写软件。店主可以使用键盘进行计费或条形码扫描仪。我不知道他会事先使用哪一个。他可能会在未来的某个时候添加其他扫描方式,例如 RFID。

所以我有以下内容:

interface IInputDevice
{
    public void PerformInput();
}

class KeyboardInput : IInputDevice
{
    public void PerformInput()
    {
        Console.Writeline("Keyboard");      
    }  
}

class BarcodeInput : IInputDevice
{
    public void PerformInput()
    {
        Console.Writeline("Barcode");             
    }
}

class Program
{
    static void Main()
    {
        IKernel kernel = new StandardKernel(new TestModule());

        var inputDevice = kernel.Get<IInputDevice>();

        inputDevice.PerformInput();

        Console.ReadLine();
    }
}

public class TestModule : Ninject.Modules.NinjectModule
{
    public override void Load()
    {
        Bind<IInputDevice>().To<....>();
    }
}

那么,我怎样才能用最少的自定义代码来实现呢?我想请求具体的代码示例,而不是指向有关上下文绑定的文章/wikis/教程的链接。

【问题讨论】:

    标签: .net dependency-injection ninject contextual-binding


    【解决方案1】:

    您需要一些标准来决定使用哪一个。例如。 App.config 或设备检测。然后使用条件绑定:

    Bind<IInputDevice>().To<KeyboardInput>().When(KeyboardIsConfigured);
    Bind<IInputDevice>().To<BarcodeInput>().When(BarcodeReaderIsConfigured);
    
    public bool KeyboardIsConfigured(IContext ctx)
    {
        // Some code to decide if the keyboard shall be used
    }
    
    public bool BarcodeReaderIsConfigured(IContext ctx)
    {
        // Some code to decide if the barcode reader shall be used
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多