1

I have a project that is using CQRS and Dependency Injection. The Query side of the system is fine.

For the command side of the system I have chosen to use a queue:

BlockingQueue<Command> commandQueue;

This stores the commands as they are received along with their arguments from multiple threads. The commands all implement a common interface with an execute method:

public interface Command extends Serializable {
    void execute();
}

The arguments for the Commands are stored as data in the concrete implementations of the Command interface. The types and potentially number of arguments will vary depending on which command it represents, using this structure means that this detail is all encapsulated away from the command queue logic.

The idea is that the commands are later executed in sequence by a worker thread which calls execute() on each Command in turn without caring about which command it is under the hood.

The commands only require injection once they are taken off the queue ready for execution (this is mostly because I would like to be able to serialize commands, but also because the execution of commands needs different modules to the part of the application that receives and queues them)

My problem is this: Because the commands need to wait until they are taken off the queue to get their dependencies, I end up passing a lightly wrapped Injector to their 'execute' method so they can create themselves an object graph. This feels more like the Service Locator pattern than Dependency Injection.

public interface Command extends Serializable {
    void execute(**ExecutorLocator locator**);
}

Is there something I'm missing or is it inevitable that DI has to look like a service locator at some point in the stack?

1 Answer 1

2

It's been a while since I laid my hands on Java code but good architecture and design is not bound to a language.

First: ServiceLocator is an anti-pattern.

Second: Tell, don't ask. If anything build-up the commands from the outside and don't let them ask a locator for their dependencies.

Third: I would create handlers that are registered for the commands and know how to handle the information encapsulated in the commands. Thus you would not need to inject or build-up your commands at all. Setup your handlers and make sure your commands get there.

1
  • I think that Logger.getLogger(SomeClass.class) is a valid use of the Service locator. However I'm not a fan in general, hence the question. Thanks for the Handlers idea, I will work with that and leave some more info if I make it work in a neater way.
    – Dave E
    Aug 15, 2012 at 19:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.