在运行时Ninject上下文绑定

时间:2011-05-29 20:27:37

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

我试图了解Ninject Contextual Binding。我理解在设计时我了解我的背景的场景。例如我知道当我想在测试类中使用它时,我可以使用命名属性将数据库对象绑定到模拟数据库,当我从实际代码中使用它时,可以使用命名属性绑定到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<....>();
    }
}

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

1 个答案:

答案 0 :(得分: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
}
相关问题