在Ninject3中有一个新的.ToConstructor feature。
如上所述,强类型构造函数参数有助于:
Bind<IMyService>().ToConstructor(
ctorArg => new MyService(ctorArg.Inject<IFoo>(), ctorArg.Inject<IBar>()));
以几乎相同的方式使用 .ToConstructor 和 .ToMethod 之间的区别是什么:
Bind<IMyService>().ToMethod(
x => new MyService(x.Kernel.Get<IFoo>(), x.Kernel.Get<IBar>()));
避免使用 Kernel.Get&lt;&gt;()这只是一种语法糖还是还有一些我缺少的东西?
答案 0 :(得分:29)
第一种情况与To<MyService>()
的行为类似,只是您明确选择了构造函数。这意味着上下文通过MyService
传递,您可以使用IFoo
和IBar
的条件或其中一个dpenpendencies,在第二种情况下,您可以获得IFoo
的新上下文和IBar
,你不会知道它们被注入MyService
。
e.g。
Bind<IFoo>().To<FooA>().WhenInjectedInto<MyService>();
Bind<IFoo>().To<FooB>().WhenInjectedInto<MyOtherService>();
在第二种情况下不起作用。