【问题标题】:Ninject Pass Delegate into WithConstructorArgumentNinject 将委托传递给 WithConstructorArgument
【发布时间】:2012-03-19 09:32:01
【问题描述】:

我需要在 Ninject 绑定中指向一个方法作为构造函数参数的一部分。该类的构造函数如下所示:

MyObject(Func<Populator> param1, TimeSpan time)

我一直在寻找并且无法找到一种方法来绑定 Func 的委托。这甚至可能吗? Ninject 不允许我这样做,因为它期望一个对象作为参数,并且不会接受委托。

Bind<IInterface>()
      .To<MyObject>()
      .InSingletonScope()
      .WithConstructorArgument
            ("param1", ctx => ctx.Kernel.Get<OtherWiredObject>().PopMethod)
      .WithConstructorArgument
            ("time", new TimeSpan(0,30,0));

有没有办法让这种行为在 Ninject 中起作用?

【问题讨论】:

  • 重载似乎是针对回调函数的。如果你是 () =&gt; Kernel.Get&lt;OtherWiredObject&gt;().PopMethod 呢?
  • 没有骰子,将其连接为 '() => Kernel.Get().PopMethod' 查看 WithConstructorArgument 方法签名,Func 期望返回一个对象,并且我需要将 Func 返回到参数。也许还有其他方法可以解决这个问题?
  • PopMethod 类型的属性Populator
  • 如果PopMethod 是一个返回Populator 的函数,则将() 添加到它的末尾...通过创建一个有效的Func&lt;Populator&gt;

标签: c# ninject ioc-container ninject-2


【解决方案1】:

你可以像这样定义一个绑定:

Bind<Func<Populator>>().ToMethod(ctx => ctx.Kernel.Get<OtherWiredObject>().PopMethod);

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    相关资源
    最近更新 更多