Getting started with nServiceBus

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 server is offline". It's an amazing feature, suppose that a client makes a request, what will happen if the server be inaccessible? With nServiceBus and its asynchronous fire & forget 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, 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 so this create a class with this definition:

  1.    public class Messaging : IMessage
  2.     {
  3.         public string Message { get; set; }
  4.     }

Now create the SendMessage class with like this:

  1.    public class SendingMessage
  2.     {
  3.         public IBus Bus { get; set; }
  4.        
  5.         public void Run()
  6.         {
  7.             Bus.SendLocal<Messaging>(m => m.Message = "nServiceBus message");
  8.         }
  9.     }

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:

  1.     public class CommandHandler : IHandleMessages<Messaging>
  2.     {
  3.         private readonly IBus _bus;
  4.  
  5.         public CommandHandler(IBus bus)
  6.         {
  7.             _bus = bus;
  8.         }
  9.  
  10.         public void Handle(Messaging message)
  11.         {
  12.             throw new NotImplementedException();
  13.         }
  14.     }

 

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.


Tags: C# SOA nServiceBus


comments powered by Disqus