本文介绍了在运行时Ninject上下文绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Ninject上下文绑定.我了解在设计时就知道自己的上下文的场景.例如我知道我可以使用命名属性将数据库对象绑定到模拟数据库(要在测试类中使用),也可以绑定到SQL DB(当我从实际代码中使用它时).

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.

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

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.

所以我有以下内容:

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/教程.

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.

推荐答案

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

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
}

这篇关于在运行时Ninject上下文绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 11:13