什么时候适合直接依赖 IoC 容器本身?
我即将创建一个可以处理不同类型的 WorkItems 的 WorkQueueService 。对于每种类型的 WorkItem,我都会有一个 IWorkItemProcessor 的实现。我正在使用 IoC,因此所有 IWorkItemProcessor 实现都将在容器中注册。我的 WorkQueueService 将需要为每个 WorkItem 获取适当的处理器。
问题是我应该让我的 WorkQueueService 直接依赖于容器吗?或者我应该将这个责任抽象到一个 WorkItemProcessorFactory 中,它只是 IoC 容器的一个薄包装?
其他人在这种情况下做了什么,为什么?
I'm just about to create a WorkQueueService that can handle different type of WorkItems. For each type of WorkItem, I will have an implementation of IWorkItemProcessor. I'm using IoC, so all the IWorkItemProcessor implementations will be registered in the container. My WorkQueueService will need to obtain the appropriate Processor for each WorkItem.
The question is should I make my WorkQueueService depend directly on the the container? Or should I abstract this responsibility into a WorkItemProcessorFactory which would be just a thin wrapper around the IoC container?
What have other people done in this situation, and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
建议您通过创建工厂来抽象容器。只有工厂才应该了解集装箱。它有两个好处:
IOC 容器,因为工厂很好地抽象了;将来它可能会被更好的容器取代。
与 IOC 容器交互的知识/复杂性被封装在一个定义良好的工厂中。团队中的所有成员无需了解特定 IOC 容器的功能。
It is recommended that you abstract containers by creating factories. Only the factories should be aware of containers. There are two benefits to it:
IOC container since well abstracted by factories; it could be replaced by a better container in future.
Knowledge/Complexity of interacting with IOC container is encapsulated in a well defined factory. All the members on the team need not be aware on the functioning of a particular IOC container.
IoC容器是一个工厂。我认为包装它没有意义,除非您认为要交换不同的实现。
抽象是美妙的,但在某些时候所有的分层都必须结束,你必须编写一个具体的实现。我认为包装 IoC 容器没有任何价值。
为什么依赖性必须是明确的?如果 WorkQueueService 有一个 IWorkItemProcessor 集合,其数量可以在 IoC 中配置,为什么不像其他依赖项一样注入该集合呢?我不明白为什么 WorkQueueService 需要对 IoC 容器的引用。
The IoC container IS a factory. I see no point in wrapping it, unless you think you're going to swap different implementations in and out.
Abstractions are wonderful, but at some point all the layering has to end and you've got to write a concrete implementation. I see no value in wrapping the IoC container.
Why must the dependence be explicit? If the WorkQueueService has a collection of IWorkItemProcessor, the number of which is configurable in your IoC, why not just inject the collection like any other dependency? I don't see why the WorkQueueService needs a reference to the IoC container.