Ninject基础与示例请 [英] Ninject basics with example please

查看:95
本文介绍了Ninject基础与示例请的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:

DI和Ninject相当新,但是很想掌握它,以便我知道自己在做什么以及为什么.

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.

谢谢.

推荐答案

Self 绑定声明了自身的某种类型的绑定.具有无参数构造函数的类型不需要自绑定. Ninject可以自己实例化这些类型.如果声明自绑定,即Bind<Sword>().ToSelf();,则只能执行Get<Sword>.例如,Get<ISword>会抛出ActivationException.

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.

方法绑定允许您指定一种方法,该方法负责创建绑定类型的实例.例如,您可以执行以下操作:Bind<ISword>().ToMethod(() => new Sword(strength = 12));您可以在ninject Wiki上看到更多示例: https://github.com/ninject/ninject/wiki/Dependency-Injection-With-Ninject

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

这篇关于Ninject基础与示例请的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆