Share via


Publishing and Subscribing using NServiceBus

NServiceBus is one of the widely used service bus for .NET.  

In this wiki let’s see how we can write a application where some application publishes events and another application consumes those.

Let's start off with the application by creating a blank solution named “NServiceBusPublishSubscribeSample”:

http://lh6.ggpht.com/-3-H3XBfwwFg/U_1p_-QFeNI/AAAAAAAACkc/lar5LLFIj3U/image_thumb12.png?imgmax=800
Adding a blank solution

For this solution, let's add three class library projects named “NServiceBusPublishSubscribeSample.Publisher”, “NServiceBusPublishSubscribeSample.Subscriber” and “NServiceBusPublishSubscribeSample.Messages”. Let's delete default Class1.cs from all the three projects. Now Let's run NServiceBus.Host nuget package on “NServiceBusPublishSubscribeSample.Publisher” and “NServiceBusPublishSubscribeSample.Subscriber” projects using Package Manager Console.

 

Install on Publisher

http://lh3.ggpht.com/-rle-qHgjsy8/U_1qCoGT98I/AAAAAAAACks/E9zGhNNrD3s/image_thumb13.png?imgmax=800
Installing NServiceBus.Host on publisher project.

Install on Subscriber

http://lh5.ggpht.com/-Kd0CWoBw0ts/U_1qFS3qtbI/AAAAAAAACk8/9QnAa28-EF0/image_thumb14.png?imgmax=800
Installing NServiceBus.Host on subscriber project.

Once Install on Package Manager Console completed installing all the required files, you can see in both “NServiceBusPublishSubscribeSample.Publisher” and “NServiceBusPublishSubscribeSample.Subscriber” projects, there is a new class added named “EndpointConfig”.

 

Now let’s move into Publisher Project and modify the “EndpointConfig” class as follows:

public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{
    public void Init()
    }
}

Here the AsA_Server is changed into AsA_Publisher. In addition let's implement IWantCustomInitialization interface on “EndpointConfig” and it is giving us a method to implement named “Init()”. For now, let's keep it as it is.

Now let's add a new class there named “MyTask” and implement an interface named IWantToRunWhenBusStartsAndStops on “MyTask”.

public class MyTask : IWantToRunWhenBusStartsAndStops
{
    public IBus Bus { get; set; }
    public void Start()
    {
 

    }

 
    public void Stop()
    {
    }
}

Now here in “Start()”, the expectation is to publish some messages which the subscribed clients can consume. For that between the Publisher and Subscriber, we need to share messages. Those messages, let's put in Messages Project. Let'a add new class named “MyMessage” inside Messages project.

There we have a single property named “Message” of type string.

public class MyMessage 
{
    public string Message { get; set; }
}

Then let's add references from both Publisher and Subscriber to Messages project.

Now moving back to Publisher project, let's modify the “Start()” method in “MyTask” as follows.

public class MyTask : IWantToRunWhenBusStartsAndStops
{
    public IBus Bus { get; set; }
    public void Start()
    {
        Bus.Publish(new MyMessage()
        {
            Message = "Hello World!"
        });
        Console.WriteLine("Published a message.");
    }
 
    public void Stop()
    {
    }
}

Now inside the Subscriber project, let's modify the “EndpointConfig” as same as Publisher project.

public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
{
    public void Init()
    {
 
    }
}

Here AsA_Server was kept as it is.  “EndpointConfig” is implementing IWantCustomInitialization interface and “Init()” was kept as it is.

Now Iet's add a class named “MessageSubscriber” and implement an interface named “IHandleMessages<T>”. In this case it’s “IHandleMessages<MyMessage>”.

public class MessageSubscriber : IHandleMessages<MyMessage>
{
    public void Handle(MyMessage message)
    {
        Console.WriteLine(message.Message);
    }
}

Now we are all set. Next what we need to do is configuring the end points of publisher and subscriber. For that let’s modify the “Init()” method in both “EndpointConfig” classes in both Publisher and Subscriber projects.

EndpointConfig in Publisher

namespace NServiceBusPublishSubscribeSample.Publisher
{
    using NServiceBus;
    public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
    {
        public void Init()
        {
            Configure
                .With()
                .DefaultBuilder()
                .DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("NServiceBusPublishSubscribeSample.Messages"));
        }
    }
}

EndpointConfig in Subscriber

namespace NServiceBusPublishSubscribeSample.Subscriber
{
    using NServiceBus;
    public class EndpointConfig : IConfigureThisEndpoint, AsA_Server, IWantCustomInitialization
    {
        public void Init()
        {
            Configure
                .With()
                .DefaultBuilder()
                .DefiningEventsAs(t => t.Namespace != null && t.Namespace.StartsWith("NServiceBusPublishSubscribeSample.Messages"));
        }
    }
}

Here both end points were configured with Fluent API. Once this is done, there is only one part left to get this up and running. Still our Subscriber doesn't know where to listen for events. For that we need to modify the <UnicastBusConfig /> section in Subscriber projects’ app.config file as follows.

<UnicastBusConfig>
    <MessageEndpointMappings>
        <add Assembly="NServiceBusPublishSubscribeSample.Messages" Endpoint="NServiceBusPublishSubscribeSample.Publisher" />
    </MessageEndpointMappings>
</UnicastBusConfig>

Now since we need to run multiple projects, let's select multiple startup projects.

http://lh3.ggpht.com/-83ikZRhxNIs/U_1qIZJkgQI/AAAAAAAAClM/jjEdnzvckaY/image_thumb19.png?imgmax=800
Setting multiple startup projects

Now when we run the project, we will be getting the following output.

http://lh3.ggpht.com/-CvwcACJ0nUE/U_1qLWYI-0I/AAAAAAAAClc/3e73yRIPXm4/SNAGHTML1c5dbc74_thumb2.png?imgmax=800
Output

Can you imagine, if it hadn't been for NServiceBus, how much of coding we will need to write  implement such a scenario.

The full sample code is uploaded to MSDN Code Gallery.
   Download Sample

Happy Coding.