Перейти до вмісту

Azure Service Bus client integration

Цей контент ще не доступний вашою мовою.

Azure Service Bus logo

The Aspire Azure Service Bus client integration is used to connect to an Azure Service Bus service. To get started with the Aspire Azure Service Bus client integration, install the 📦 Aspire.Azure.Messaging.ServiceBus NuGet package:

.NET CLI — Add Aspire.Azure.Messaging.ServiceBus package
dotnet add package Aspire.Azure.Messaging.ServiceBus

For an introduction to working with the Azure Service Bus client integration, see Get started with the Azure Service Bus integration.

In the Program.cs file of your client-consuming project, call the AddAzureServiceBusClient extension method on any IHostApplicationBuilder to register a ServiceBusClient for use via the dependency injection container. The method takes a connection name parameter.

builder.AddAzureServiceBusClient(connectionName: "messaging");

You can then retrieve the ServiceBusClient instance using dependency injection. For example, to retrieve the connection from an example service:

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

For more information on dependency injection, see .NET dependency injection.

When you call AddAzureServiceBusClient(), the correct value depends on the object you passed to the client in the AppHost.

For example, if you use this code in the AppHost:

var serviceBus = builder.AddAzureServiceBus("messaging");
var apiService = builder.AddProject<Projects.Example_ApiService>("apiservice")
.WithReference(serviceBus);

Then the correct code to add the Service Bus in your client-consuming program is:

builder.AddAzureServiceBusClient(connectionName: "messaging");

However, if you created and passed a Service Bus topic in the AppHost:

var serviceBus = builder.AddAzureServiceBus("messaging");
var topic = serviceBus.AddServiceBusTopic("myTopic");
var apiService = builder.AddProject<Projects.Example_ApiService>("apiservice")
.WithReference(topic);

Then the correct code to add the Service Bus topic in your client-consuming program is:

builder.AddAzureServiceBusClient(connectionName: "myTopic");

For more information, see Add Azure Service Bus resource and Add Azure Service Bus topic and subscription.

Properties of the Azure Service Bus resources

Section titled “Properties of the Azure Service Bus resources”

When you use the WithReference method to pass an Azure Service Bus resource from the AppHost project to a consuming client project, several properties are available to use in the consuming project.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called servicebus becomes SERVICEBUS_URI.

The Azure Service Bus namespace resource exposes the following connection properties:

Property NameDescription
HostThe namespace hostname
UriThe service endpoint URI

In emulator mode, additional properties are available:

Property NameDescription
HostThe local emulator host
PortThe local emulator port
UriThe service bus URI
ConnectionStringThe full connection string for the emulator

The Azure Service Bus queue resource inherits all properties from its parent namespace and adds:

Property NameDescription
QueueNameThe queue name

The Azure Service Bus topic resource inherits all properties from its parent namespace and adds:

Property NameDescription
TopicNameThe topic name

The Azure Service Bus subscription resource inherits all properties from its parent topic and adds:

Property NameDescription
SubscriptionNameThe subscription name

For example, if you reference a queue resource named queue in your AppHost project, the following environment variables will be available in the consuming project:

  • QUEUE_HOST
  • QUEUE_URI
  • QUEUE_QUEUENAME

There might be situations where you want to register multiple ServiceBusClient instances with different connection names. To register keyed Service Bus clients, call the AddKeyedAzureServiceBusClient method:

builder.AddKeyedAzureServiceBusClient(name: "mainBus");
builder.AddKeyedAzureServiceBusClient(name: "loggingBus");

Then you can retrieve the ServiceBusClient instances using dependency injection. For example, to retrieve the connection from an example service:

public class ExampleService(
[FromKeyedServices("mainBus")] ServiceBusClient mainBusClient,
[FromKeyedServices("loggingBus")] ServiceBusClient loggingBusClient)
{
// Use clients...
}

For more information on keyed services, see .NET dependency injection: Keyed services.

The Aspire Azure Service Bus integration provides multiple options to configure the connection based on the requirements and conventions of your project.

When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling the AddAzureServiceBusClient method:

builder.AddAzureServiceBusClient("messaging");

Then the connection string is retrieved from the ConnectionStrings configuration section:

{
"ConnectionStrings": {
"messaging": "Endpoint=sb://{namespace}.servicebus.windows.net/;SharedAccessKeyName={keyName};SharedAccessKey={key};"
}
}

The Aspire Azure Service Bus integration supports Microsoft.Extensions.Configuration. It loads the AzureMessagingServiceBusSettings from configuration by using the Aspire:Azure:Messaging:ServiceBus key. The following snippet is an example of an appsettings.json file that configures some of the options:

{
"Aspire": {
"Azure": {
"Messaging": {
"ServiceBus": {
"ConnectionString": "Endpoint=sb://{namespace}.servicebus.windows.net/;SharedAccessKeyName={keyName};SharedAccessKey={key};",
"DisableTracing": false
}
}
}
}
}

For the complete Service Bus client integration JSON schema, see Aspire.Azure.Messaging.ServiceBus/ConfigurationSchema.json.

The Aspire Azure Service Bus integration supports named configuration, which allows you to configure multiple instances of the same resource type with different settings. The named configuration uses the connection name as a key under the main configuration section.

{
"Aspire": {
"Azure": {
"Messaging": {
"ServiceBus": {
"bus1": {
"ConnectionString": "Endpoint=sb://namespace1.servicebus.windows.net/;SharedAccessKeyName=keyName;SharedAccessKey=key;",
"DisableTracing": false
},
"bus2": {
"ConnectionString": "Endpoint=sb://namespace2.servicebus.windows.net/;SharedAccessKeyName=keyName;SharedAccessKey=key;",
"DisableTracing": true
}
}
}
}
}
}

In this example, the bus1 and bus2 connection names can be used when calling AddAzureServiceBusClient:

builder.AddAzureServiceBusClient("bus1");
builder.AddAzureServiceBusClient("bus2");

Named configuration takes precedence over the top-level configuration. If both are provided, the settings from the named configuration override the top-level settings.

You can also pass the Action<AzureMessagingServiceBusSettings> configureSettings delegate to set up some or all the options inline, for example to disable tracing from code:

builder.AddAzureServiceBusClient(
"messaging",
static settings => settings.DisableTracing = true);

You can also set up the ServiceBusClientOptions using the optional Action<ServiceBusClientOptions> configureClientOptions parameter of the AddAzureServiceBusClient method. For example, to set the Identifier user-agent header suffix for all requests issued by this client:

builder.AddAzureServiceBusClient(
"messaging",
configureClientOptions:
clientOptions => clientOptions.Identifier = "myapp");

By default, Aspire integrations enable health checks for all services. For more information, see Aspire integrations overview.

The Aspire Azure Service Bus integration:

  • Adds the health check when DisableTracing is false, which attempts to connect to the Service Bus.
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic.

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

The Aspire Azure Service Bus integration uses the following log categories:

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

In addition to getting Azure Service Bus request diagnostics for failed requests, you can configure latency thresholds to determine which successful Azure Service Bus request diagnostics will be logged. The default values are 100 ms for point operations and 500 ms for non point operations.

builder.AddAzureServiceBusClient(
"messaging",
configureClientOptions:
clientOptions => {
clientOptions.ServiceBusClientTelemetryOptions = new()
{
ServiceBusThresholdOptions = new()
{
PointOperationLatencyThreshold = TimeSpan.FromMilliseconds(50),
NonPointOperationLatencyThreshold = TimeSpan.FromMilliseconds(300)
}
};
});

The Aspire Azure Service Bus integration 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

Azure Service Bus tracing is currently in preview, so you must set the experimental switch to ensure traces are emitted.

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

For more information, see Azure Service Bus: Distributed tracing and correlation through Service Bus messaging.

The Aspire Azure Service Bus integration currently doesn’t support metrics by default due to limitations with the Azure SDK.