Ninject basics with example please

流过昼夜 提交于 2019-12-10 20:37:10

问题


Scenario:

Quite new to DI and Ninject but would love to master it so that I know what'm doing and why.

While going through few examples and documentation I noticed the following:

1. ToConstructor.
2. ToMethod
3. Self

If someone could help me to understand when and how above can be used, will be good. An example will be good.

Thanks.


回答1:


Hy,

Self bindings declare a binding of a certain type to itself. Self bindings are not needed for types which have a parameterless constructor. Ninject can instantiate these types on its own. If you declare a self binding, i.e. Bind<Sword>().ToSelf(); it is only possible to do a Get<Sword>. For example Get<ISword> would throw an ActivationException.

Method bindings allow you to specify a method which is responsible to create an instance of the binded type. For example you can do the following: Bind<ISword>().ToMethod(() => new Sword(strength = 12)); You can see more example on the ninject wiki here: https://github.com/ninject/ninject/wiki/Dependency-Injection-With-Ninject



来源:https://stackoverflow.com/questions/11218830/ninject-basics-with-example-please

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