A Trip to CQRS – Events

This is part 3 of 5. The entire series is here:

    1. Intro
    2. Commands
    3. Events
    4. Authoritative Events
    5. New Views

In my last post, the system was introduced to Commands in order to structure the code a bit and make sure to separate the updates from the reads. Now it’s time to actually bring in some business value!

Remember, the two new requirements we had was to 1) Log all changes, and 2) Pass change information to other systems in near real-time. And what better to handle this than Events?

Our events are simple DTOs, usually mapping more or less exactly to a Command:

[github file=”/andlju/hotel-admin/blob/events/src/HotelAdmin.Messages/Events/HotelAddedEvent.cs” start_line=”4″ end_line=”20″]

CQRS Events

Now, usually in a “proper” DDD-ES-CQRS system (D-DDD or whatever you’d like to call it) we would let the domain objects publish these events whenever an interesting action has occurred. Unfortunately, we are not blessed with a nice DDD model, instead we have our Command Handlers that use the very Anemic Domain Model (curtsey of Entity Framework) to push updates to the database. Instead, we’ll simply let the Command Handlers publish events themselves.

[github file=”/andlju/hotel-admin/blob/events/src/HotelAdmin.Service/CommandHandlers/AddHotelCommandHandler.cs” start_line=”24″ end_line=”52″]

Events are published to an event store (which happens to be EventStore in this case). The event store is responsible for, well, storing the events and also sending them off to anyone else who might be interested (represented as Event Handlers in the diagram). For integrating with downstream system, something like a Service Bus would probably be a good thing to put in here.

Testing

Testing with this scenario looks very much the same as testing in the last one, but now we also make sure that the published Events are looking good.

[github file=”/andlju/hotel-admin/blob/events/src/HotelAdmin.Service.Tests/CommandHandlers/AddHotel/When_Handling_AddHotelCommand.cs” start_line=”10″ end_line=”103″]

Benefits

Well, we now have our complete log of all changes in the system (the Event Store). We also have a quite extensible mechanism for doing real-time integration (using a Service Bus, EventHandlers etc..)! So, we’re done, right?

Nope. I’m afraid not. Because there is one, quite major, flaw in this system. And that will be the topic for the next post!



2 responses to “A Trip to CQRS – Events”

  1. I don’t seem to spot the code that actually publishes the event. Am I missing something?

    Like

    1. Thanks, I was showing code from the wrong branch. Fixed now!

      Like

Leave a comment

About Me

Consultant, Solution Architect, Developer.

Do note that this blog is very, very old. Please consider that before you follow any of the advice in here!

Newsletter