What's the difference between .ToConstructor and .ToMethod in Ninject 3?

心不动则不痛 提交于 2019-11-29 10:41:51

问题


In Ninject3 there's a new .ToConstructor feature.

As described, it helps to strongly-type constructor arguments like:

Bind<IMyService>().ToConstructor(
    ctorArg => new MyService(ctorArg.Inject<IFoo>(), ctorArg.Inject<IBar>()));

What's actually the difference between using .ToConstructor and .ToMethod in an almost the same way:

Bind<IMyService>().ToMethod(
    x => new MyService(x.Kernel.Get<IFoo>(), x.Kernel.Get<IBar>()));

Is it just a syntax sugar to avoid using Kernel.Get<>() or is there something more that I'm missing?


回答1:


The first case behaves like To<MyService>() except that you explicitly select the constructor. This means the context is passed through MyService and you can use conditions for IFoo and IBar or one of their dpependencies where in the second case you get a new context for IFoo and IBar and you will not know that they are injected into MyService.

e.g.

Bind<IFoo>().To<FooA>().WhenInjectedInto<MyService>();
Bind<IFoo>().To<FooB>().WhenInjectedInto<MyOtherService>();

will not work in the second case.



来源:https://stackoverflow.com/questions/8777475/whats-the-difference-between-toconstructor-and-tomethod-in-ninject-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!