Blog

Filter posts by Category Or Tag of the Blog section!

Getting started with nServiceBus

Wednesday, 02 October 2013

When I read about nServiceBus or work with that it reminds me that "If it is complicated, you're probably doing it wrong". nServiceBus is really an amazing service platform for distributed systems and messaging. 

 

What is nServiceBus!?

nServiceBus is the most popular service platform for Dot Net. It's a powerful messaging framework for designing distributed .NET enterprise systems. nServiceBus gives you a scalable, and maintainable service-layers and long-running business processes. nServiceBus is structured around a bus which you can put messages and message handlers. It makes communicating with services much easier and incorporates true service-oriented architecture. The main communication pattern behind NServiceBus is a pattern called "publish and subscribe".

By using nServiceBus a "Client can send messages if the server is offline". It's an amazing feature, suppose that a client makes a request, what will happen if the server is inaccessible? With nServiceBus and its asynchronous fire & forget the messaging pattern

 

 

nServiceBus messaging example

let's deep into nServiceBus implementation, create a simple class library and reference the NServiceBus, NServiceBus.Core, NServiceBus.Host.  If you get nServiceBus via Nuget, the package will take care of the configuration for you. Your App.config should be something like this:

nServiceBus

I'm just going to implement a simple messaging with nServiceBus, in order to do this create a class with this definition:

 

   public class Messaging : IMessage
    {
        public string Message { get; set; }
    }

 

Now create the SendMessage class with like this:

 

   public class SendingMessage
    {
        public IBus Bus { get; set; }
       
        public void Run()
        {
            Bus.SendLocal<Messaging>(m => m.Message = "nServiceBus message");
        }
    }

 

In this class by using the Bus property of nServiceBus you send the message locally, now you can create your CommandHandler  class to handle the message:

 

    public class CommandHandler : IHandleMessages<Messaging>
    {
        private readonly IBus _bus;

        public CommandHandler(IBus bus)
        {
            _bus = bus;
        }

        public void Handle(Messaging message)
        {
            throw new NotImplementedException();
        }
    }

 

This class will get invoked automatically when the Message(of Messaging class) arrives, you can handle the message and have it in a console output or something else. for more information about nServiceBus I recommend to read this articles.

comments powered by Disqus