Azure Service Bus client integration
此内容尚不支持你的语言。
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:
dotnet add package Aspire.Azure.Messaging.ServiceBus#:package Aspire.Azure.Messaging.ServiceBus@*<PackageReference Include="Aspire.Azure.Messaging.ServiceBus" Version="*" />For an introduction to working with the Azure Service Bus client integration, see Get started with the Azure Service Bus integration.
Add Service Bus client
Section titled “Add Service Bus client”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.
Choose the correct connection name
Section titled “Choose the correct connection name”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.
Azure Service Bus namespace
Section titled “Azure Service Bus namespace”The Azure Service Bus namespace resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The namespace hostname |
Uri | The service endpoint URI |
In emulator mode, additional properties are available:
| Property Name | Description |
|---|---|
Host | The local emulator host |
Port | The local emulator port |
Uri | The service bus URI |
ConnectionString | The full connection string for the emulator |
Azure Service Bus queue
Section titled “Azure Service Bus queue”The Azure Service Bus queue resource inherits all properties from its parent namespace and adds:
| Property Name | Description |
|---|---|
QueueName | The queue name |
Azure Service Bus topic
Section titled “Azure Service Bus topic”The Azure Service Bus topic resource inherits all properties from its parent namespace and adds:
| Property Name | Description |
|---|---|
TopicName | The topic name |
Azure Service Bus subscription
Section titled “Azure Service Bus subscription”The Azure Service Bus subscription resource inherits all properties from its parent topic and adds:
| Property Name | Description |
|---|---|
SubscriptionName | The 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_HOSTQUEUE_URIQUEUE_QUEUENAME
Add keyed Service Bus client
Section titled “Add keyed Service Bus client”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.
Configuration
Section titled “Configuration”The Aspire Azure Service Bus integration provides multiple options to configure the connection based on the requirements and conventions of your project.
Use a connection string
Section titled “Use a connection string”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};" }}Use configuration providers
Section titled “Use configuration providers”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.
Use named configuration
Section titled “Use named configuration”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.
Use inline delegates
Section titled “Use inline delegates”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");Client integration health checks
Section titled “Client integration health checks”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
DisableTracingisfalse, which attempts to connect to the Service Bus. - Integrates with the
/healthHTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”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.
Logging
Section titled “Logging”The Aspire Azure Service Bus integration uses the following log categories:
Azure.CoreAzure.IdentityAzure-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) } }; });Tracing
Section titled “Tracing”The Aspire Azure Service Bus integration will emit the following tracing activities using OpenTelemetry:
MessageServiceBusSender.SendServiceBusSender.ScheduleServiceBusSender.CancelServiceBusReceiver.ReceiveServiceBusReceiver.ReceiveDeferredServiceBusReceiver.PeekServiceBusReceiver.AbandonServiceBusReceiver.CompleteServiceBusReceiver.DeadLetterServiceBusReceiver.DeferServiceBusReceiver.RenewMessageLockServiceBusSessionReceiver.RenewSessionLockServiceBusSessionReceiver.GetSessionStateServiceBusSessionReceiver.SetSessionStateServiceBusProcessor.ProcessMessageServiceBusSessionProcessor.ProcessSessionMessageServiceBusRuleManager.CreateRuleServiceBusRuleManager.DeleteRuleServiceBusRuleManager.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.
Metrics
Section titled “Metrics”The Aspire Azure Service Bus integration currently doesn’t support metrics by default due to limitations with the Azure SDK.