ninjectninject-2

Ninject basics with example please


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.


Solution

  • 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