Unity 容器应该在哪里创建并解析引用?
假设我有一个哈希组件,通过名为 IHash 的服务合约调用。我有一个需要使用哈希的组件 DLL。我们使用 Unity 创建一个松散耦合的系统。
我应该创建 Unity 容器并解析组件 DLL 本身中的引用吗?
或者我应该在组件 DLL 构造函数中传递 IHash 引用,并让组件 DLL 的调用者处理 Unity 容器并解析 IHash。
public myComponentDLL(IHash Hasher) { }
看来如果我创建容器并在组件 DLL 中解析它,Unity 并不会太买账。我发现在构造函数中传递它有更大的好处。
除了上述两种方法之外还有更好的方法吗?这是一个好的做法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 Unity 传递给组件并不是一个好的做法,您无法通过查看其构造函数来了解它的依赖关系,因为它只需要
IUnityContainer
,天知道里面会有多少个解析构造函数。最佳实践是通过构造函数传递接口(就像您所做的那样),并使用组件接口统一解析组件。在解析您的组件时,统一选择 IHash 并注入它。
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.
应用程序中唯一应引用 IoC 容器的位置是应用程序的根目录。您在这里注册所有组件并解析程序的根组件。然后,Unity 将满足根组件所需的所有依赖关系以及所有这些组件的依赖关系,依此类推,直到构建整个依赖关系图。请参阅 http:// devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container 了解更多信息。
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.