In a project I am working on at the moment I have designed and helped implement a MSMQ based service bus which allows us to run processes that have to retrieve data from external systems on machines outside of our web-farm (it’s a SharePoint 2010 Publishing solution). This allows us to offload the multi-threaded socket gobbling monster webservice calls to somewhere that wont impact the operations of the rest of the site. Also the way it is written made me think of how we could use it for CQRS and other high volume storage implementations.

To achieve all of this we basically have this sort of design:

This allows us to send messages through a generic sender class which will raise an event through a delegate whenever a message is received. In our usage of this we have messages that ask for a web service call to be executed and when the data is returned down the bus messages are routed into the database or returned to a waiting thread depending on some app logic.

A simple implementation of this bus is as follows:

    public class MSMQReceiver : IDisposable
    {
        readonly MessageQueue queue;

        public MessageReceived OnMessageReceived { get; set; }

        public MSMQReceiver()
        {
            queue = new MessageQueue("queue_name");
        }

        public void StartListening()
        {
            queue.ReceiveCompleted += queue_ReceiveCompleted;
            queue.BeginReceive();
        }

        void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            queue.EndReceive(e.AsyncResult);
            queue.BeginReceive();

            OnMessageReceived(e.Message.Body);
        }

        public void Dispose()
        {
            queue.ReceiveCompleted -= queue_ReceiveCompleted;
            queue.Close();
            queue.Dispose();
        }
    }

    public delegate void MessageReceived(object data);

The above code creates a message queue (or attaches to one if it exists) that will asynchronously listen for messages. When a message is received it will put the body of the message into an object and fire off the delegate for you to what you want with it. This is only a very simple example, but it allows you to expand it and it provides the pattern to create a larger disconnected architecture that leads to interesting challenges like horizontal scaling in a cloud environment or maybe your first home-brew CQRS implementation.