.NET Aspire Azure Service Bus component

Cloud-native apps often require communication with messaging services such as Azure Service Bus. Messaging services help decouple applications and enable scenarios that rely on features such as queues, topics and subscriptions, atomic transactions, load balancing, and more. The .NET Aspire Service Bus component handles the following concerns to connect your app to Azure Service Bus:

  • A ServiceBusClient is registered in the DI container for connecting to Azure Service Bus.
  • Applies ServiceBusClient configurations either inline through code or through configuration file settings.

Prerequisites

Get started

To get started with the .NET Aspire Azure Service Bus component, install the Aspire.Azure.Messaging.ServiceBus NuGet package.

dotnet add package Aspire.Azure.Messaging.ServiceBus

For more information, see dotnet add package or Manage package dependencies in .NET applications.

Example usage

In the Program.cs file of your component-consuming project, call the AddAzureServiceBusClient extension to register a ServiceBusClient for use via the dependency injection container.

builder.AddAzureServiceBusClient("messaging");

To retrieve the configured ServiceBusClient instance using dependency injection, require it as a constructor parameter. For example, to retrieve the client from an example service:

public class ExampleService(ServiceBusClient client)
{
    // ...
}

App host usage

To add Azure Service Bus hosting support to your IDistributedApplicationBuilder, install the Aspire.Hosting.Azure.ServiceBus NuGet package.

dotnet add package Aspire.Hosting.Azure.ServiceBus

In your app host project, register the Service Bus component and consume the service using the following methods:

var builder = DistributedApplication.CreateBuilder(args);

var serviceBus = builder.ExecutionContext.IsPublishMode
    ? builder.AddAzureServiceBus("messaging")
    : builder.AddConnectionString("messaging");

builder.AddProject<Projects.ExampleProject>()
       .WithReference(serviceBus)

Configuration

The .NET Aspire Service Bus component provides multiple options to configure the ServiceBusClient based on the requirements and conventions of your project.

Use configuration providers

The Service Bus component supports Microsoft.Extensions.Configuration. It loads the AzureMessagingServiceBusSettings from appsettings.json or other configuration files using Aspire:Azure:Messaging:ServiceBus key.

{
  "Aspire": {
    "Azure": {
      "Messaging": {
        "ServiceBus": {
          "DisableHealthChecks": true,
          "DisableTracing": false,
          "ClientOptions": {
            "Identifier": "CLIENT_ID"
          }
        }
      }
    }
  }
}

If you have set up your configurations in the Aspire:Azure:Messaging:ServiceBus section of your appsettings.json file you can just call the method AddAzureServiceBus without passing any parameters.

Use inline delegates

You can also pass the Action<AzureMessagingServiceBusSettings> delegate to set up some or all the options inline, for example to set the FullyQualifiedNamespace:

builder.AddAzureServiceBus(
    "messaging",
    static settings => settings.FullyQualifiedNamespace = "YOUR_SERVICE_BUS_NAMESPACE");

You can also set up the ServiceBusClientOptions using Action<IAzureClientBuilder<ServiceBusClient, ServiceBusClientOptions>> delegate, the second parameter of the AddAzureServiceBus method. For example to set the ServiceBusClient ID to identify the client:

builder.AddAzureServiceBus(
    "messaging",
    static clientBuilder =>
        clientBuilder.ConfigureOptions(
            static options => options.Identifier = "CLIENT_ID"));

Named instances

If you want to add more than one ServiceBusClient you can use named instances. Load the named configuration section from the JSON config by calling the AddAzureServiceBus method and passing in the INSTANCE_NAME.

builder.AddAzureServiceBus("INSTANCE_NAME");

The corresponding configuration JSON is defined as follows:

{
  "Aspire": {
    "Azure": {
      "Messaging": {
        "INSTANCE_NAME": {
          "FullyQualifiedNamespace": "YOUR_SERVICE_BUS_NAMESPACE",
          "ClientOptions": {
            "Identifier": "CLIENT_ID"
          }
        }
      }
    }
  }
}

Configuration options

The following configurable options are exposed through the AzureMessagingServiceBusSettings class:

Name Description
ConnectionString The connection string used to connect to the Service Bus namespace.
Credential The credential used to authenticate to the Service Bus namespace.
FullyQualifiedNamespace The fully qualified Service Bus namespace.
DisableTracing Disables tracing for the Service Bus client.
HealthCheckQueueName The name of the queue used for health checks.
HealthCheckTopicName The name of the topic used for health checks.

At least one of the name options are mandatory when enabling health checks.

Observability and telemetry

.NET Aspire components automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about component observability and telemetry, see .NET Aspire components overview. Depending on the backing service, some components may only support some of these features. For example, some components support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.

Logging

The .NET Aspire Azure Service Bus component uses the following log categories:

  • Azure.Core
  • Azure.Identity
  • Azure-Messaging-ServiceBus

Tracing

Note

Service Bus ActivitySource support in the Azure SDK for .NET is experimental, and the shape of activities may change in the future without notice.

You can enable tracing in several ways:

  • Setting the Azure.Experimental.EnableActivitySource runtime configuration setting to true. Which can be done with either:

    • Call AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);.

    • Add the RuntimeHostConfigurationOption setting to your project file:

      <ItemGroup>
          <RuntimeHostConfigurationOption
               Include="Azure.Experimental.EnableActivitySource"
               Value="true" />
      </ItemGroup>
      
  • Set the AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE environment variable to "true".

    • Can be achieved by chaining a call to WithEnvironment("AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE", "true")

When enabled, the .NET Aspire Azure Service Bus component will emit the following tracing activities using OpenTelemetry:

  • Message
  • ServiceBusSender.Send
  • ServiceBusSender.Schedule
  • ServiceBusSender.Cancel
  • ServiceBusReceiver.Receive
  • ServiceBusReceiver.ReceiveDeferred
  • ServiceBusReceiver.Peek
  • ServiceBusReceiver.Abandon
  • ServiceBusReceiver.Complete
  • ServiceBusReceiver.DeadLetter
  • ServiceBusReceiver.Defer
  • ServiceBusReceiver.RenewMessageLock
  • ServiceBusSessionReceiver.RenewSessionLock
  • ServiceBusSessionReceiver.GetSessionState
  • ServiceBusSessionReceiver.SetSessionState
  • ServiceBusProcessor.ProcessMessage
  • ServiceBusSessionProcessor.ProcessSessionMessage
  • ServiceBusRuleManager.CreateRule
  • ServiceBusRuleManager.DeleteRule
  • ServiceBusRuleManager.GetRules

For more information, see:

Metrics

The .NET Aspire Azure Service Bus component currently doesn't support metrics by default due to limitations with the Azure SDK for .NET. If that changes in the future, this section will be updated to reflect those changes.

See also