Fun with Windows Server Service Bus and AutoFac – Part 1 – The Service Bus

In this post we´ll have a look at using the Windows Server Service Bus in a Pub/Sub scenario. The Windows Server Bus is the on-premise version of Azure service bus. Moving between on-premise and Azure deployment should be as easy as changing connection string. What’s interesting with this is the support for other platforms, like node.js in Azure, using the same infrastructure. Enabling you to do small modules/services with the platform/language best suited for the scenario working together with for example the Azure Service Bus. For this post we’re going to be on-premise in C# land.

We’ll create simple contract for publishing an subscribing to messages through something like this;

public interface IServiceBus
    void Subscribe<T>(IHandle<T> handler);
    void Publish<T>(T message);

Then we’re going to add support for registering subscribes in an Autofac container, so the end result looks something like this (covered in part 2);

var container = new ContainerBuilder()

You’ll find all the demo code for this post (and part 2) on GitHub, to go along, as this post will only show some code of the core parts of the solution.

When I started looking at this scenario I found another project by Brady Gaster called The Azure Service Bus Simplifier from which I draw some inspiration.

Ok, lets get going. But first some information on the Service Bus infrastructure….

Service Bus

Take a good look or even stare at the image above. It shows some key concepts we’re going to use. We’re going to send messages on a Topic using the TopicClient to send/publish our messages.

Our subscribers will then use subscriptions to listen for this messages via an SubscriptionClient. The neat thing as the image illustrates is that we can have several subscription clients listening on the same topic, with different configuration/behavior. In the scenario above there is one subscription for auditing and one for business logic.


To install Windows Service Bus you need the installer and a SQL instance (localDB, express, full, 2008 SP1 or higher) on a x64 machine.

Note if you run localDB remember that our default instance is probably (localDB)v11.0. Full installation instructions here.


The SDK is a nuget package with the Microsoft.ServiceBus assembly, named Service Bus 1.0 for Windows Server. So you just need to add this to your project.

The application

With the Service Bus installed you could create a project and reference the nuget package. The service bus supports configuration of the connectionstring in the *.config file.

To use this, you first need your current settings for you installation. The Service Bus installation added a Service Bus Powershell short cut. Find this and run it. From here you can configure you bus. Use the following command to get your configuration;


Add this information to your configuration file, looking something like this;

    <add key="Microsoft.ServiceBus.ConnectionString"
RuntimePort=9354;ManagementPort=9355" />

With this in place we could start creating Topics and Subscriptions and the clients for these.

Publish a message

To publish a message, you need a Topic and then a TopicClient to send the message. So the action of publishing could look like this;

public void Publish<T>(T message)
    var topicClient = _topicClientFactory.CreateFor<T>();
        topicClient.Send(new BrokeredMessage(message));
    catch (Exception x)
        throw x;

What’s going on here? We need a client for a Topic, here we have a factory that creates a client based on a Topic named after the type. The factory is custom code, but the BrokeredMessage is from the Service Bus SDK.

To create the client we use the MessagingFactory, part of the SDK.

public TopicClient CreateFor<T>()
    var topicName = string.Format("Topic_{0}", typeof(T).Name);
    return _messagingFactory.CreateTopicClient(topicName);

So publishing was pretty straight forward in this simple scenario. Let´s look at the subscribers.

Subscribing to a message

Ok, as mentioned earlier, subscriptions is done via a SubscribtionClient and we could have several for the same Topic.

public SubscriptionClient CreateFor<T>()
    var subscription = _subscriptionRepository.Get<T>();
    var topicPath = subscription.TopicPath;

    return _messagingFactory.CreateSubscriptionClient(topicPath,
                subscription.Name, ReceiveMode.ReceiveAndDelete);

So, what’s going here? We’re getting the subscription for a Type, much like the Topic. To create a SubscriptionDescription you need the TopicPath as with Topic we name the Subscription by type. The subscription name is then used when we create SubscriptionClient.

Note that if you have several applications or interests as in the audit scenario, you need to have individual names for each subscription. A simple type convention could lead to trouble.

Also note, the ReceiveMode, there are to modes. PeekLock and ReceiveAndDelete.  The latter removes the message from the subscription directly. PeekLock lets you grab the message and lock it and the do stuff and call complete or keep it on the queue. ReceiveAndDelete doesn’t leave us any room for errors in our subscribers.

public SubscriptionDescription Get<T>()

    SubscriptionDescription subscription;

    if (!_namespaceManager.SubscriptionExists(topic.Path,
        subscription = _namespaceManager
            .CreateSubscription(topic.Path, subscriptionName);
        subscription = _namespaceManager
            .GetSubscription(topic.Path, subscriptionName);

    return subscription;

Subscriptions is created via the NamespaceManager, a part of the SDK.

When we have our SubscriptionClient we can start to retrieve messages. There are a lot of options for this part. Our code is quite simple.

Given a client we start listening for messages, then end retrieval. We then read the message, gets the body (our object). With the message at hand we give it to the delegate for execution. We then begins to listen for new messages.

public void Receive<T>(SubscriptionClient subscriptionClient,
                        Action<T> action)
        (cb) =>
            var brokeredMessage = subscriptionClient.EndReceive(cb);
            if (brokeredMessage != null)
                var messageData = brokeredMessage.GetBody<T>();
                Receive(subscriptionClient, action);

Note that the action could be delegating the message to multiple handlers. The interaction with the subscriptionclient is an interesting extension point, for configuration per message subscription.

That’s the core part of our subscription infrastructure. We then add handling for multiple subscribers for a message on top of this. And in the next part, handling both subscription handlers for our container as well as delegates at the same time.


We’ve looked at the parts closest to the Service Bus in this post. The NamespaceManager and MessagingFactory is used for creating Topics and Subscribers  and clients for those. ReceiveMode comes in two flavors, we used a simple model with RetreiveAndDelete for now. Receiving messages on a subscription could be configured a lot more.
The core parts are a quick refactoring of Brady’s ServiceBusSimplifier, an exercise I could see as a possible Code Kata,  since it’s functional and a small context, learning pub/sub and the service bus.

You’ll find the code @ github so you could play/fork/refactor away!  In next part we’ll take a look at the AutoFac configuration extensions, another play area where we could swap and configure our small parts.


This Post Has 3 Comments

  1. Nuri

    sample code has problem. could you please fix?

Leave a Reply