Ninject Contextual Binding at RunTime

2020-07-17 14:55发布

问题:

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
}