Let's say I have a hash component called with a service contract called IHash. I have a component DLL that needs to use hashing. We are usign Unity to create a loosely coupled system.
Should I create the Unity container and resolve the reference in the component DLL itself?
Or should I pass a IHash reference in the component DLL contructor and let the caller of the component DLL deal with the Unity container and resolving IHash.
public myComponentDLL(IHash Hasher) { }
It seems if I create the container and resolve it in the component DLL, Unity is not buying me too much. I see a greater benefit in passing it in the constructor.
Is there a better way other than the two methods described above? Is this a good practice?
Passing unity to the component is not a good practice, you don't know the dependencies of it by looking at its constructor, as it will take only IUnityContainer
, and god knows how many resolves will be there inside the constructor.
Best practice is to pass the interface through constructor (as you have done) and also resolve your component in unity using your components interface. While resolving your component unity picks IHash and injects it.
The only place in your application where your IoC container should be referenced is the root of the application. You register all your components here and resolve the program's root component. Unity will then satisfy all dependencies that the root component requires and the dependencies of all those components and so on until the whole dependency graph is built. See http://devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With