Ninject将委托传递到WithConstructorArgument中

本文关键字:WithConstructorArgument Ninject | 更新日期: 2023-09-27 18:26:07

我需要将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中发挥作用?

Ninject将委托传递到WithConstructorArgument中

您可以定义这样的绑定:

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