Ninject Contextual Binding at RunTime

。_饼干妹妹 提交于 2020-01-01 11:48:17

问题


I am trying to understand Ninject Contextual Binding. I understand the scenarios where I know my context at design time. e.g. I understand that I can use Named Attributes to Bind the DB object to a mock DB when I want to use it in a test class and to a SQL DB when I use it from my actual code.

However, I don't know how to handle contextual Binding at runtime. e.g. let's say I am writing software for a shopping center. The shopkeeper can use a keyboad for billing or a barcode scanner. I don't know which one he will use beforehand. And he might add other ways of scanning like RFID sometime in the future.

So I have the following:

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<....>();
    }
}

So, how can I go about it in the least amount of custom code? I would like to request specific code examples and not links to articles/wikis/tutorials on contextual binding.


回答1:


You will need some criteria to decide which one shall be used. E.g. App.config or device detection. Then use conditional bindings:

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
}


来源:https://stackoverflow.com/questions/6170233/ninject-contextual-binding-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!