views:

38

answers:

2

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?

A: 

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.

duffymo
@duffymo: I suppose I could give the WorkQueueService a collection of WorkItemProcessors, but then it would need to hunt through the collection to find the appropriate type for each work item: I'd rather give the container that reposnsibility one way or another.
Samuel Jack
+3  A: 

It is recommended that you abstract containers by creating factories. Only the factories should be aware of containers. There are two benefits to it:

  1. IOC container since well abstracted by factories; it could be replaced by a better container in future.

  2. 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.

Anand Patel
+1 Abstract Factory is a very common solution to this kind of DI challenges. You should never take a dependency directly on the container.
Mark Seemann