gpt4 book ai didi

.net - Ninject 运行时上下文绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 07:55:48 24 4
gpt4 key购买 nike

我正在尝试理解 Ninject 上下文绑定(bind)。我了解在设计时了解我的上下文的场景。例如据我所知,当我想在测试类中使用它时,我可以使用命名属性将数据库对象绑定(bind)到模拟数据库,而当我从实际代码中使用它时,我可以使用命名属性将它绑定(bind)到 SQL 数据库。

但是,我不知道如何在运行时处理上下文绑定(bind)。例如假设我正在为购物中心编写软件。店主可以使用键盘或条形码扫描仪进行计费。我不知道他事先会用哪一个。他可能会在未来某个时候添加其他扫描方式,例如 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<....>();
}
}

那么,我怎样才能用最少的自定义代码来完成它呢?我想请求具体的代码示例,而不是有关上下文绑定(bind)的文章/维基/教程的链接。

最佳答案

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

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
}

关于.net - Ninject 运行时上下文绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6170233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com