Today we are going to talk about CQS (Command Query Separation). In this blog post i will focus on the command part. Commands are simple objects that instruct our application to do something. I will show you the most simple implementation possible, combined with the power of Castle Windsor, which will act as our command handler registry.
Let’s show the basic duo, namely our command and it’s respective handler.
The ‘ICommand’ interface acts as a marker interface to mark all of our commands in our code base. Let’s take the example model from my previous blog post as a starting point for our first command:
And it’s dedicated handler:
The Bus acts as the primal communication point in our application, it’s responsibility is too send command’s, directly we add a single command send and a multiple command send, so we can use this later as a facade for our unitofwork/transaction setup.
The dispatcher’s primary role is execute the handler of the command given. Later we could use this to do for instance validation on our commands.
Show me the code
A possible bus implementation, that will invoke the dispatcher’s generic dispatch method:
And an example implementation of our dispatcher, which will use a commandhandler factory to get the respective handler:
The ICommandHandlerFactory is fully implemented by Castle Windsor’s TypedFactory facility, and if you are wondering why the release code, please read my post about understanding memory leaks with Castle Windsor.
The commanding facility
All necessary registration’s nicely molded into a custom facility:
So to use this code, just register all of your commandhandlers, best with a lifestyle of transient, add TypedFactoryFacility and CommandFacility into the mix and start commanding yourself:
The code, and the supplementary unit tests, are available on Github.