Tuesday 27 October 2009

Commands and Events

In my last post I ended with talking about sending messages between bounded contexts. In this post I want to describe how to do this, but I also want to talk about a new thing I want to try out. It is called Command and Query Responsibility Segregation (CQRS).

Please leave a message to tell me if you understand it or not?

With CQRS you are basically splitting the commands from the queries (Inserts, updates, deletes from the selects :)). This means that we can optimise how we show data on the user interface and how we handle changes.

From the user interface we send "Commands" to the domain. These commands will modify the aggregate roots and save the changes. These changes are translated into "Events" which are saved. When we want to get our aggregate root, we simple have to playback all the events to get our state. This means we have a nice log of what has happened with the object.

An example

"Ok, sounds nice, but how does it work?" you may say.. Lets look at a simplified example:
The user wants to create a new radio program into the system. After clicking on the "New" button, the UI does something like:
_commandBus.Send(new CreateRadioProgramCommand(Guid.NewGuid(), _programName));

In the domain we have a CreateRadioProgramCommandHandler class which will create a new RadioProgram object and save it to the Repository.
While creating the RadioProgram a CreateRadioProgramEvent will be created. This event will be saved in the database and will be published. By publishing the event the event can be used to update the query cache so that the user can find the RadioProgram in the user interface.

Updating the radio

Now that we have a Radio Program, the user can use the user interface to change details of the Radio Program. So when we have changed things, the UI does something like:
_commandBus.Send(new ChangeRadioProgramLanguage(_id, "Dutch"));

The ChangeRadioProgramLanguageCommandHandler will ask the repository for the correct radio program. The repository will get all previous events and use those to construct the Radio Program.
Then the Language will be changed and the Radio Program will be saved.
This causes a new event, LanguageChangedEvent and this event will be published so that the UI cache will be changed.

Communicating with Bounded Contexts?

At this point I am not really curtain how the communication between Bounded Contexts can be established. I think it could be both "Events" AND "Commands" or "Events" that are leading to "Commands"

No comments:

Post a Comment

Note: only a member of this blog may post a comment.