Prash's Blog

Introduction to NServiceBus July 28, 2014

Filed under: C# — prazjain @ 4:39 pm
Tags: ,

It is a light weight communication framework used generally in a heterogeneous environment where different applications, all using different technologies, need to communicate with each other.

What is a ServiceBus
When do I need one


Getting Binaries


  • Download NServiceBus.
    • From the installation options, just select NServiceBus (and unselect the rest, we do not need them for this tutorial). This will also setup MSMQ, Distribute Transaction Coordinator (DTC), RavenDB database, Performance counters, Lucene etc.
    • RavenDB will get installed as windows service, stop the windows service. Install latest version of Raven from official website. Navigate to services and make sure it is now running latest version of RavenDB.
    • Check RavenDB is setup by visiting url : http://localhost:8080/raven/studio.html

RavenDB home page

  • Check queues under Computer Management -> Services and Application -> Message Queuing. (Right click on “My Computer” -> Manage : To reach at Computer Management screen)

Computer Management - Queues

  • Install NuGet Package Manager
    • Go to Visual Studio -> Tools -> Extension and Updates and download as depicted below

Install NuGet Package Manager



  •  Lets create a console project and call it Console.Request and name the solution ServiceBus. This project will contain code that generates messages.

Console.Request project

  • Now that we have defined our Message, let go back to Console.Request project and use this message type.In Console.Request project, open App.config file and add the below code:
     <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
     <add Messages="App.Contracts" Endpoint="backendQueue" />

    The above configuration allows any messages defined in namespace App.Contracts to be sent to “backendQueue”. This allows us to change the destination of messages based on their type, without changing the code.

    Until now, we have defined a message type and associated a queue with particular types of messages. To be able to send message we need to write code to send it. Add OrderGenerator class as below to Console.Request project:

    public class OrderGenerator
     public OrderGenerator()
     // Lets configure the bus using Fluent API
     Bus = Configure.With().Log4Net().DefaultBuilder().UseTransport&lt;Msmq&gt;().UnicastBus().SendOnly();
     public IBus Bus { get; set; }
     public Guid NewOrder()
     var order = new PlaceOrder
     OrderId = Guid.NewGuid(),
     ProductId = Guid.NewGuid(),
     CustomerId = Guid.NewGuid()
     return order.OrderId;

    Next, update your Program.cs file in Console.Request as follows:

    class Program
     static void Main(string[] args)
     OrderGenerator orderGenerator = new OrderGenerator();
     while (true)
     System.Console.WriteLine("Generated new Order id :" + orderGenerator.NewOrder());

    Now lets run the code we have so far. You are on right track if you see message as below:


  • Include NServiceBus libraries in the project
    • Go to Visual Studio -> View -> OtherWindows -> Package Manager Console. Run the command on prompt
      PM> install-package nservicebus
    • Messages are common types that will be needed by all projects / libraries. So we will create messages in a separate library project.
      • Create a new library project “App.Contracts”.
        • Go to Package Manager Console. Run the command
          PM> install-package nservicebus-interfaces

          In this project we do not need the entire nservice bus library package, we just need the interface to define nservice bus messages, so we install just the interfaces.

      • Lets create a sample message as below:
        namespace App.Contracts
            /// &lt;summary&gt;
            /// This is a message type. Any NServiceBus message needs to implement marker interface IMessage.
            /// &lt;/summary&gt;
            public class PlaceOrder : IMessage
                public Guid ProductId { get; set; }
                public Guid OrderId { get; set; }
                public Guid CustomerId { get; set; }


In NServiceBus, it is the responsibility of the hosting process to create the queue. Until now we have only written the requesting process, so the queue does not exists and requesting process is surely complaining about it.

Lets go ahead and create the queue ourselves. Create a private transactional queue as shown below, as NServiceBus uses private and transactional queues.

create backendQueue

Once the queue is created, run the program again. (Press enter a few times to generate more messages) If it has completed successfully, you can check the queue again (refresh if needed).




Console will show message like this:

Generated new Order id : 21217e71-1ec0-4c1b-a333-38a9b7d9c6a8

Message queue will look like this:

backendQueue message body

Xml is a bit like this:

<?xml version="1.0"?>
<Messages xmlns:xsi="" xmlns:xsd="" xmlns="">

This is it!

We wrote ‘producer’ application (application generating messages) that can send messages using NServiceBus, to be used by another application.

In the second part to this post, we will see how a ServiceBus Host application is written using NServiceBus. This second application can then be used to process messages we have in the queue.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s