Unity is a pretty neat piece of work, it’s a simple and straightforward dependency injection container and it gets the job done, which is all you want from any implementation like this.
If someone’s trying to go beyond the “get an implementation instance for a given interface” examples found in most of the tutorials then proper dependency injection will be the way to go. This means returning the proper instance for the given interface, but also properly the objects that instance needs, and also the objects needed by those objects, and this could go on forever. Unity can do this almost automatically, but to do so it may need hints on how objects should be created, specially to choose the right constructor when multiple are available (by default will choose the fatest of them all).
One of the ways this problem is solved is using an attribute that indicates which constructor should be used (the same is valid for either properties and method calls), as shown below:
public class MyClass
{
public MyObject(SomeOtherClass myObjA)
{
...
}
[InjectionConstructor]
public MyObject(MyDependentClass myObjB)
{
...
}
}
The problem is: Unity, and all other dependency injection containers, want to solve a simple issue: reduce coupling between modules, classes, etc. That’s achieved by removing the dependency to the proper implementation, you only have to know the contract to use (the interface) and the dependency injection container will return the proper implementation, whatever that may be. But, by doing this we’re adding another dependency: to the dependency injection container implementation (like Unity), and while this is reasonable for the class that needs to use the container is not so reasonable for the classes the container will use.
Take the code sample above: MyClass is just a plain class, by adding the InjectionConstructor attribute we’re adding a needless dependency because that class will never use Unity, it will be used by Unity. For me using this can be a design flaw that goes against what dependency injection is supposed to achieve. A safer, but more time consuming, way to get around this is to explicitly configure those dependencies (either in design time or run time) instead of letting Unity try to figure them out.
Technorati Tags: microsoft,enterprise library,dependency injection,unity,ioc
Share this: |
|
|
|
|
|


