Ninject Mini Tutorial - Part 2
Go to Part 1
Controlling the Life Cycle of your Objects
In the previous post we did not concern ourselves with the lifecycle of the object returned from Ninject kernel. Ninject provides the following 4 built-in lifecycles (scopes):
- Transient (default)
- Singleton (only one instance)
- Thread (one instance per thread)
- Request (one instance per web request).
You can create custom scopes if needed.
Singleton:
Transient:
More Details on Injection Patterns
With Ninject you can inject:
- Constructor parameters
- Properties
- Methods
Before considering each one in turn, we just need to introduce the [Inject]
attribute which may be
used to tag constructors, properties and methods requiring injection.
Obviously, by tagging constructors, properties or methods, your objects cease
to be POCOs.
Constructor Injection
We have already seen an example of constructor injection in Part I
when the kernel auto-magically injected an implementation of ITaxCalculator
to the Sale Area
constructor.
In that case, even if we didn't tag the constructor with the [Inject]
attribute, the kernel was able to
perform the required binding. How?
That was actually a special case: when there is only one constructor available,
the tagging is not needed. On the other hand, if there's more than one constructor defined,
then then kernel can inject a dependency to only one constructor that needs to have the [Inject]
attribute:
Properties Injection
Instead of passing in the dependencies through the constructor, you can also inject them as properties. Injecting properties is pretty straightforward:
Usage (note that we never explicitely set the TaxCalculator
):
There's an important caveat: if you have 2 or more properties injected, the order in which each dependency is injected is not predictable. This might complicate your design, if those dependencies are coupled somehow (e.g. dependency A needs dependency B). For this kind of situations, constructor or method injection is usually preferred.
Methods Injection
Finally, it's also possible to tag methods for injection. As with constructor parameters, its possible to inject more than one value at once.
Usage (note that we never explicitely call the SetTaxCalculator
):
Go to Part 1
Leave a Comment