在运行时Ninject上下文绑定

Yas*_*sir 4 .net dependency-injection ninject contextual-binding

我试图理解Ninject Contextual Binding.我理解在设计时我了解我的背景的场景.例如,当我想在测试类中使用它时,我可以使用命名属性将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<....>();
    }
}
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能用最少量的自定义代码来实现呢?我想请求特定的代码示例,而不是关于上下文绑定的文章/ wiki /教程的链接.

Rem*_*oor 7

您需要一些标准来决定使用哪一个.例如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
}
Run Code Online (Sandbox Code Playgroud)