Second part of my series on Unity. For an introduction, read the first post.
OK, now we know how to get Inversion of Control (IoC): instead of referencing a particular concrete implementation, we instead reference an interface or an abstract base class, which creates a level of abstraction and allows us to change things at a later time.
Now let’s see what Unity has to offer in terms of Dependency Injection (DI). DI is the process by which objects are populated (injected) with values, called dependencies, usually coming from the IoC container itself. Basically, we have three options for that:
- Constructor injection;
- Property injection;
- Method injection.
What this means is, when asked for a particular instance, Unity will call a constructor, set a property’s value or invoke a method with a parameter coming from its registration. Say you have a class like this:
Unity can inject the Logger instance by either passing a parameter on the constructor when building an instance of the MyService class, directly setting the Logger property (even with a private setter) or by invoking the SetLogger method.
Injection By Configuration
As we have seen, most things in Unity can be configured by XML configuration:
Did you notice the dependencyName attribute? That is the name under which the dependencyType was registered, if not set, it defaults to the empty string.
I have included both constructor, property and method injection, you usually will only need one of them.
Injection By Code
Another option is by code. When registering a type, you must add some additional code:
Injection By Attributes
Another option is by applying attributes:
The File string is the name of the registered type.
Injecting Dependencies On Existing Entities
If you have some object instance that was obtained elsewhere, you can still ask Unity to inject whatever dependencies this object has. This is achieved by the BuildUp family of methods:
Next in line: applying aspects. Stay tuned!