Samuel Jack
Samuel Jack

Reputation: 33280

When is it appropriate to take a direct dependency on the IoC container itself?

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?

Upvotes: 1

Views: 84

Answers (2)

Anand Patel
Anand Patel

Reputation: 6431

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.

Upvotes: 3

duffymo
duffymo

Reputation: 308998

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.

Upvotes: 0

Related Questions