Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should Unity containers be created and references be resolved?

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?

like image 740
Jon Raynor Avatar asked Feb 24 '23 16:02

Jon Raynor


2 Answers

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.

like image 113
anivas Avatar answered Feb 26 '23 05:02

anivas


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.

like image 34
MangoBrainz Avatar answered Feb 26 '23 04:02

MangoBrainz