Skip to content

How to Run Azure Service Bus Locally using .NET Aspire

Testing cloud-native applications often feels like a balancing act. You either pay for a dedicated “Dev” environment in the cloud or spend hours configuring complex mocks. With .NET Aspire, that struggle is over.

In this post, we’ll look at how to leverage the Azure Service Bus Emulator within .NET Aspire to get a fully functional messaging system running on your machine in minutes.

Why .NET Aspire?

.NET Aspire is an opinionated, cloud-ready stack for building observable, production-ready distributed applications. One of its “superpowers” is the ability to orchestrate resources (like databases or message brokers) using C# code.

Prerequisites

  • .NET 8.0/9.0+ SDK
  • Docker Desktop or Podman (required to run the emulator container)
  • Visual Studio 2022 (17.10+) or VS Code with C# Dev Kit

Step 1: Add the Service Bus Resource

In your .AppHost project, you need to define the Service Bus resource. Since we want to run it locally, .NET Aspire will automatically spin up the Azure Service Bus Emulator inside a container.

var builder = DistributedApplication.CreateBuilder(args);

// Add Azure Service Bus resource
var messaging = builder.AddAzureServiceBus("messaging")
                       .RunAsEmulator(); // This is where the magic happens!

// Reference the service in your API or Worker
builder.AddProject<Projects.MyApiService>("apiservice")
       .WithReference(messaging);

builder.Build().Run();

Step 2: Configure the Client Project

In your consumer or producer project (e.g., MyApiService), add the Aspire Azure Service Bus integration package:

dotnet add package Aspire.Azure.Messaging.ServiceBus

Then, simply register the client in Program.cs:

builder.AddAzureServiceBusClient("messaging");

Step 3: Send and Receive Messages

Now you can inject ServiceBusClient anywhere in your code without worrying about connection strings. Aspire handles the “wiring” automatically.

app.MapPost("/send", async (ServiceBusClient client) =>
{
    var sender = client.CreateSender("my-queue");
    await sender.SendMessageAsync(new ServiceBusMessage("Hello, Local World!"));
    return Results.Ok("Message sent!");
});

Summary

By using RunAsEmulator(), you gain:

  1. Cost savings: No cloud charges for local development.
  2. Performance: Zero latency compared to cloud endpoints.
  3. Offline capability: Code on the plane, in a train, or anywhere without Wi-Fi.
Tags: