# Getting Started With NServiceBus in .NET

> NServiceBus is a feature-rich messaging framework supporting many different message transports. Its basic building blocks are messages and endpoints. I'll show you how to configure an endpoint for Azure Service Bus, publish messages with IMessageSession, and handle them with IHandleMessages.

Published: 2023-10-07. Author: Milan Jovanović.

Canonical: https://milanjovanovic.tech/blog/getting-started-with-nservicebus-in-dotnet

To get started with NServiceBus, install the `NServiceBus.Extensions.Hosting` package, call `UseNServiceBus` on the host, and configure a transport such as Azure Service Bus.
Then define messages as `ICommand`, `IEvent`, or `IMessage` classes, publish them through `IMessageSession`, and handle them by implementing `IHandleMessages<T>`.

NServiceBus is a feature-rich messaging framework supporting many different message transports.
It's developed and maintained by [Particular Software.](https://particular.net/)
And it simplifies the process of building complex distributed systems across various cloud-based queueing technologies.

The basic building blocks of NServiceBus are messages and endpoints.
A message contains the required information to execute a business operation.
Endpoints are logical entities that send and receive messages.

And now let's see how to get started with NServiceBus, from installation and setup to building your first NServiceBus endpoint.

In this week's newsletter, you will learn how to:

- Configure an endpoint to use Azure Service Bus
- Send and publish messages using `IMessageSession`
- Handle messages with NServiceBus

Let's dive in!

## What is NServiceBus?

[NServiceBus](https://go.particular.net/milanjovanovic) is a messaging framework and platform that simplifies building reliable, scalable, and maintainable distributed systems.
It's designed to address the challenges that arise when building applications that are distributed across multiple servers.

One of NServiceBus's foundational principles is its embrace of a message-driven architecture.
In this model, components communicate by sending and receiving messages.
Messages are the fundamental units of communication, representing commands, events, or data that services exchange.

Why is this significant?

Message-driven architectures offer several advantages:

- Asynchronous communication
- Loose coupling
- Reliability

NServiceBus supports the powerful publish/subscribe (pub/sub) messaging pattern.
This pattern allows services to publish events and subscribe to events of interest.
When a service publishes an event, all interested subscribers receive a copy of the event.
This is a key feature for building [**event-driven architectures**](https://milanjovanovic.tech/blog/event-driven-architecture-in-dotnet-with-rabbitmq), where services react to and process events in response to various actions or changes in the system.

## Configuring the NServiceBus Endpoint

NServiceBus uses the concept of an _endpoint_ to send and receive messages.
It's a logical component that communicates with other components.
You define your message handlers and sagas inside of an endpoint.

Let's start by installing the `NServiceBus` NuGet package:

```powershell
Install-Package NServiceBus.Extensions.Hosting
```

Now you can configure an _endpoint_ to use [Azure Service Bus](https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview)
to send messages:

```csharp
var builder = WebApplication.CreateBuilder();

builder.Host.UseNServiceBus(context =>
{
    var endpointConfiguration = new EndpointConfiguration("Training");

    var transport = endpointConfiguration
        .UseTransport<AzureServiceBusTransport>();

    var connectionString = builder.Configuration
        .GetConnectionString("AzureServiceBusConnectionString");
    transport.ConnectionString(connectionString);

    endpointConfiguration.EnableInstallers();

    return endpointConfiguration;
});

var app = builder.Build();

app.Run();
```

The call to `UseNServiceBus` tells the host to use NServiceBus.
Inside the callback, you can configure the endpoint that will start when the host runs.

One more important aspect is calling `EnableInstallers` to set up the Azure Service Bus topology.
This will tell NServiceBus to create the required queues, so you don't have to do it manually.

## Publishing Messages in NServiceBus

The next building block you need in any messaging system is the messages.
Messages are C# classes or interfaces that contain meaningful data for the business process.

NServiceBus supports three types of messages:

- `ICommand` - sends a request to perform an action
- `IEvent` - communicates that something significant occurred
- `IMessage` - for messages that aren't commands or events (typically for replies in _request-response_)

Events can have more than one handler, while a command should have only one handler.

Let's create our first message contract:

```csharp
using NServiceBus;

public class WorkoutCreated : IEvent
{
    public Guid Id [ get; set; ]
}
```

The `WorkoutCreated` message is an event that we will publish after creating a new `Workout`.

You can use the `IMessageSession` service to send messages from your controllers or Minimal API endpoints.

```csharp {4,10}
app.MapPost("api/workouts", async (
    Workout workout,
    AppDbContext context,
    IMessageSession messageSession) =>
{
    context.Add(workout);

    await context.SaveChangesAsync();

    await messageSession.Publish(new  WorkoutCreated { Id = workout.Id });

    return Results.Ok(workout);
});
```

NServiceBus has some built-in validation when sending messages.
You have to specify an `ICommand` when calling the `Send` method, or you will get an exception.
Similarly, you have to specify an `IEvent` when calling the `Publish` method.

## Handling Messages With NServiceBus

Once you send a message, you need a way to handle it and run some business logic.
To handle a message, you need to implement the `IHandleMessages` interface and specify which message you are handling.

Here's an implementation of the `WorkoutCreatedHandler`:

```csharp
public class WorkoutCreatedHandler : IHandleMessages<WorkoutCreated>
{
    private readonly ILogger<WorkoutCreated> _logger;

    public WorkoutCreatedHandler(ILogger<WorkoutCreated> logger)
    {
        _logger = logger;
    }

    public async Task Handle(
        WorkoutCreated message,
        IMessageHandlerContext context)
    {
        logger.LogInformation("Processing workout - {Id}", message.Id);

        // Continue to process the message.
    }
}
```

Implementing `IHandleMessages<WorkoutCreated>` tells NServiceBus how to process the `WorkoutCreated` message when an endpoint receives it.
This interface defines only one method: `Handle`.

The `Handle` method has an `IMessageHandlerContext` parameter, which allows you to send more messages.
This can be helpful when implementing a [**choreographed saga**](https://milanjovanovic.tech/blog/saga-pattern-dotnet).
Processing one message triggers the next step in the chain until the entire process is completed.

## In Summary

In this week's issue, we discussed NServiceBus, a robust messaging framework for building distributed systems in .NET.
You learned how to configure NServiceBus with the Azure Service Bus transport.
We discussed the different message types in NServiceBus and how to publish and handle a message.

Building distributed systems is a complex endeavor, but NServiceBus simplifies many challenges.
By embracing a message-driven architecture and leveraging NServiceBus's features,
you'll be well-equipped to create resilient, scalable, and maintainable applications in the .NET ecosystem.

Further reading:

- [NServiceBus step-by-step tutorial](https://go.particular.net/milanjovanovic/getting-started-with-nservicebus)
- [Live coding an NServiceBus system](https://go.particular.net/milanjovanovic/live-coding-your-first-nservicebus-system)
- [NServiceBus monitoring demo](https://go.particular.net/milanjovanovic/monitoring-demo)
- [Messaging with Azure Service Bus](https://milanjovanovic.tech/blog/messaging-made-easy-with-azure-service-bus)
- [Implementing the Saga pattern](https://milanjovanovic.tech/blog/implementing-the-saga-pattern-with-rebus-and-rabbitmq)
- [Orchestration vs Choreography](https://milanjovanovic.tech/blog/orchestration-vs-choreography)

Hope this was helpful.

I'll see you next week!

---

## Frequently asked questions

### What is NServiceBus?

NServiceBus is a messaging framework for .NET, developed and maintained by Particular Software, that supports many message transports. It simplifies building reliable, scalable distributed systems using a message-driven architecture where components communicate by sending and receiving messages.

### What are the message types in NServiceBus?

NServiceBus supports three types: ICommand sends a request to perform an action, IEvent communicates that something significant occurred, and IMessage covers messages that are neither, typically replies in request-response. Events can have multiple handlers, while a command should have only one.

### How do I configure an NServiceBus endpoint in ASP.NET Core?

Install the NServiceBus.Extensions.Hosting package and call UseNServiceBus on the host. Inside the callback, create an EndpointConfiguration, configure a transport such as Azure Service Bus with its connection string, and call EnableInstallers so NServiceBus creates the required queues for you.

### How do I publish a message with NServiceBus?

Inject the IMessageSession service and call Publish with an IEvent, or Send with an ICommand. NServiceBus validates this at runtime: passing the wrong message type to Send or Publish throws an exception.

### How do I handle messages in NServiceBus?

Implement the IHandleMessages<T> interface for the message type and write your logic in its single Handle method. The IMessageHandlerContext parameter lets you send further messages, which is useful for choreographed sagas where each message triggers the next step.
