【问题标题】:Bind interface to multiple concrete implementation with constructor argument使用构造函数参数将接口绑定到多个具体实现
【发布时间】:2016-06-27 08:59:48
【问题描述】:

我正在尝试进行上下文绑定,但无法将具体实现接口绑定为构造函数参数。 忍者版本:3.2.0.0

我的结构如下:

INotifier 1. XNotifier 2. YNotifier

IPublisher 1.出版商 2. BPublisher

其中 XNotifier 和 YNotifier 采用 IPublisher 类型的构造函数参数。

这是我的绑定:

Bind<INotifier>()
          .To<XNotifier>()
          .When(x => notifictionControl.ToLower() == "xnotification" )
          .WithConstructorArgument("Publisher",ctx=>Kernel.Get<IPublisher>());


        Bind<INotifier>()
        .To<YNotifier>()
        .When(x => notifictionControl.ToLower() == "ynotification" )
        .WithConstructorArgument("Publisher", ctx => Kernel.Get<IPublisher>());

用法:

 IParameter parameter = new ConstructorArgument("Publisher", publisher);
        var notifier = kernel.Get<INotifier>(parameter);

但出现以下错误

激活 INotifier 时出错 没有匹配的绑定可用,并且类型不是自绑定的。

【问题讨论】:

  • 为什么要把参数传入Get&lt;INotifier&gt;
  • @MaKCbIMKo : 实现 INotifier 的类的构造函数期望 IPublisher 的具体实现。
  • 但是您已经在绑定中指定了构造函数参数。为什么你又这样做了?
  • @MaKCbIMKo:感谢您的更正。

标签: c# ninject ioc-container ninject-extensions contextual-binding


【解决方案1】:

您的示例代码使用绑定完成位置的本地值。我推测这是错误的 = 不是你想要的。

发生错误是因为在解析绑定时没有任何When 条件匹配。 或者换句话说:当 Ninject 被要求返回 INotifier 时,它将评估 INotifier 绑定的所有 When 条件,然后解析匹配的条件。

When 条件只应在运行时有时您想实例化“A”而其他时候实例化“B”时使用。如果在内核的实例化过程中已经知道要做什么,那么你应该像这样调整你的代码:

if(notifictionControl.ToLower() == "xnotification")
{
    Bind<INotifier>()...
}
else if(notifictionControl.ToLower() == "ynotification")
{
    Bind<INotifier>()...
}
else
{ 
    throw new Exception("invalid config");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多