DEV Community

Rafael Lillo
Rafael Lillo

Posted on

NServiceBus - Basic usage

NServiceBus is a project that help you to create distributed system (scalable, reliable and flexible) abstracting the queuing technology (for debug purpose we can use local file system).

Using the NServiceBus is very easy, we need a message, which can be a class or an interface that extend the IMessage and message handler class that implement IHandleMessages with the message type.

public class ProcessMessage : IMessage 
    public string Value { get; set; }

public class ProcessMessageHandler : IHandleMessages<ProcessMessage>
    // NServiceBus also provider log abstraction
    private static readonly ILog Log = LogManager.GetLogger(typeof(ProcessMessageHandler));

    public Task Handle(ProcessMessage message, IMessageHandlerContext context)    
        Log.InfoFormat("Received message with value: {0}", message.Value);
        return Task.CompletedTask;
Enter fullscreen mode Exit fullscreen mode

Before send the message is necessary to configure and start the Endpoint. An endpoint is a logical component that communicates with other components using messages. Each endpoint has an identifying name, contains a collection of message handlers and/or sagas.

An endpoint instance is a physical deployment of an endpoint. Each endpoint instance processes messages from an input queue which contains messages for the endpoint to process. Each endpoint has at least one endpoint instance. Additional endpoint instances may be added to scale-out the endpoint. A collection of endpoint instances represents a single endpoint if and only if:

  • The endpoint instances have the same name.
  • The endpoint instances contains the same collection of handlers and/or sagas.
  • The endpoint instances are deployed to the same environment.

The code bellow show how to configure and create an Endpoint instance:

var endpointConfiguration = new EndpointConfiguration("SimpleMessage");

// Using local file system

var endpointInstance = await Endpoint.Start(endpointConfiguration);

Console.WriteLine("Press 'Enter' to send a ProcessMessage message");
Console.WriteLine("Press any other key to exit");
while (true)
    if (Console.ReadKey().Key != ConsoleKey.Enter)

    var val = Guid.NewGuid();
    var startOrder = new ProcessMessage { Value = val.ToString() };
    // Send the ProcessMessage
    await endpointInstance.SendLocal(startOrder);
        Console.WriteLine($"Sent ProcessMessage with OrderId {val}.");

await endpointInstance.Stop();
Enter fullscreen mode Exit fullscreen mode

As you can see it's very easy to start coding with NServiceBus.

The main advantage of NServiceBus is your documentation, it's very well documented, and have a paid support in case of you need it.

NServiceBus Endpoint
Full code

Top comments (0)