Ninject 3中.ToConstructor和.ToMethod有什么区别?

Sha*_*dix 32 c# ninject

在Ninject3中有一个新的.ToConstructor功能.

如上所述,它有助于强类型构造函数参数,如:

Bind<IMyService>().ToConstructor(
    ctorArg => new MyService(ctorArg.Inject<IFoo>(), ctorArg.Inject<IBar>()));
Run Code Online (Sandbox Code Playgroud)

以几乎相同的方式使用.ToConstructor.ToMethod之间的区别是什么?

Bind<IMyService>().ToMethod(
    x => new MyService(x.Kernel.Get<IFoo>(), x.Kernel.Get<IBar>()));
Run Code Online (Sandbox Code Playgroud)

它只是一个语法糖,以避免使用Kernel.Get <>()或还有更多我缺少的东西?

Rem*_*oor 30

第一种情况的行为与To<MyService>()您明确选择构造函数的行为类似.这意味着背景下穿过MyService,你可以使用条件IFooIBar或他们的dpependencies其中在第二种情况下,你得到一个新的上下文中的一个IFoo,并IBar和你不会知道他们正在注入MyService.

例如

Bind<IFoo>().To<FooA>().WhenInjectedInto<MyService>();
Bind<IFoo>().To<FooB>().WhenInjectedInto<MyOtherService>();
Run Code Online (Sandbox Code Playgroud)

在第二种情况下不起作用.