开发者

Where should Unity containers be created and references be resolved?

开发者 https://www.devze.com 2023-03-19 02:57 出处:网络
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.

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 re开发者_Go百科solve 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号