Sending Commands to the Bus

Last time, we set the stage for composing the Bus so that we can tell Messages where to go when we emit them. We saw how Greg Young built the FakeBus class with a Message Routing component that’s basically a map of where a Message type (Command or Event) should be routed to which Handlers.

Another component of the Bus is the actual Message Pipeline. Essentially, we’d like to 1) send a Message to the Bus 3) find a Handler through the Message Router and 3) pass the Message to the Handle method of the Handler. But in a production system, we likely want durability in these Messages. We also want to process them in a First-In-First-Out (FIFO) sequence. We get this (and more) from solutions like NServiceBus, Rebus, MassTransit. They usually offer a variety of options to hook into infrastructure that will make messages durable like MSMQ, RabbitMQ, and SQL Server.

For now, we’re getting a prototype ready for Nick at First Pop Coffee. We’re going to refactor a more robust Service Bus solution into the app after Nick gets a look at the prototype.

Looking back at Greg Young’s definition of the FakeBus class, we see that it implements two interfaces ICommandSender and IEventPublisher.

public class FakeBus : ICommandSender, IEventPublisher {

Here are the definitions of those interfaces:

public interface ICommandSender {
    void Send<T>(T command) where T : Command;

public interface IEventPublisher {
    void Publish<T>(T @event) where T : Event;

In FakeBus, ICommandSender.Send<T>(T command) where T : Command is implemented by finding the Action<Message> registered for the given Command type:

public void Send<T>(T command) where T : Command {
    List<Action<Message>> handlers;

    if (_routes.TryGetValue(typeof(T), out handlers)) {
        if (handlers.Count != 1) throw new InvalidOperationException("cannot send to more than one handler");
    else {
        throw new InvalidOperationException("no handler registered");

Next, let’s see how this would work by writing a test for FakeBus. Click continue reading below!

continue reading…


I will be releasing most of this content only to subscribers. Make sure you sign up by clicking the big red button!

Related Posts:

comments powered by Disqus