What is NServiceBus
NServiceBus is a Microsoft .Net based framework for implementing the Enterprise Service Bus pattern. Its a framework for implementing reliable messaging through various transports without having to write boilerplate code. NServiceBus also provides facilities for pub/sub, retries, format abstraction, encryption, workflow orchestration, and scalability. Below are few highlights of the system.
- Seamlessly work with various messaging systems (Transport)
- Automatic Serialisation & De-serialisation
- Enforcing a Bus architecture
- Transaction Scope (Unit of Work)
- Simple model to handle long running transactions (Sagas)
Building a simple Unicast bus using NServiceBus
Let’s use .Net core 2.0 for building a simple bus. Everything in NServicebus can be configured using a simple class called “EndpointConfiguration”. An endpoint is a service which uses NServicebus framework for handling messages.
var endpointConfiguration = new EndpointConfiguration("UnicastBus");
NServiceBus uses persistence to store all the configuration and temporary data so that the data is not lost while there is a failure (fallacies of Network). We can configure NServiceBus persistence using the below code. We are using an In-memory persistence for the sample app. But in real applications, other reliable persistence like SQL, Raven, Azure Service fabric etc. will be used.
NserviceBus is a framework and is not a message queues on its own. However, it uses an Adapter pattern to fit any open source & commercial queuing systems. In our case, we are wiring it up with RabbitMQ (an open source message queuing system written in Erlang).
var tranportExtensions = endpointConfiguration.UseTransport<RabbitMQTransport>(); tranportExtensions.ConnectionString("host=localhost;username=guest;password=guest");
RabbitMQ also has a concept of routing topology where a user can configure how data is passed between exchanges & queues. In our case, we are going to use ‘direct routing’ topology.
tranportExtensions.UseDirectRoutingTopology(); var routing = tranportExtensions.Routing(); routing.RouteToEndpoint(assembly: typeof(Order).Assembly,destination: "Sales");
Through this configuration, we are pushing all messages coming to “Unicast Bus” exchange to “Sales” exchange. That’s it, we are good to start the Unicast bus.
var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false);
Now, sending messages using the bus that we just created is simple.
endpointInstance..Send(“My First Message using NServiceBus”);
To see the result, we should run the program and look for messages in the ‘Sales’ queue in RabbitMQ management tool.
NServiceBus is one of the frameworks for doing reliable messaging for handling the fallacies of distributed computing. This is just a gentle introduction to NServiceBus. We shall see more advanced concepts in the future posts.