Перейти к содержимому
Docs Try Aspire
Docs Try

Set up Azure Service Bus in the AppHost

Это содержимое пока не доступно на вашем языке.

Azure Service Bus logo

This article is the reference for the Aspire Azure Service Bus Hosting integration. It enumerates the AppHost APIs — with examples for both AppHost.cs and apphost.ts — that you use to model an Azure Service Bus namespace, queues, topics, and subscriptions as resources in your AppHost project.

If you’re new to the Azure Service Bus integration, start with the Get started with the Azure Service Bus integrations guide. For how consuming apps read the connection information this page exposes, see Connect to Azure Service Bus.

The following resource types are available in the hosting integration:

  • AzureServiceBusResource — represents an Azure Service Bus namespace.
  • AzureServiceBusQueueResource — represents an Azure Service Bus queue.
  • AzureServiceBusTopicResource — represents an Azure Service Bus topic.
  • AzureServiceBusSubscriptionResource — represents an Azure Service Bus subscription.
  • AzureServiceBusEmulatorResource — represents a local Azure Service Bus emulator container.

To start building an Aspire app that uses Azure Service Bus, install the 📦 Aspire.Hosting.Azure.ServiceBus NuGet package:

Terminal
aspire add azure-service-bus

Learn more about aspire add in the command reference.

Or, choose a manual installation approach:

C# — AppHost.cs
#:package Aspire.Hosting.Azure.ServiceBus@*
XML — AppHost.csproj
<PackageReference Include="Aspire.Hosting.Azure.ServiceBus" Version="*" />

Once you’ve installed the hosting integration in your AppHost project, add an Azure Service Bus namespace resource:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging");
// After adding all resources, run the app...
builder.Build().Run();

Connect to an existing Azure Service Bus namespace

Section titled “Connect to an existing Azure Service Bus namespace”

If you have an existing Azure Service Bus namespace, chain a call to AsExisting (C#) or asExisting (TypeScript) to connect to it instead of provisioning a new one:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var existingServiceBusName = builder.AddParameter("existingServiceBusName");
var existingServiceBusResourceGroup = builder.AddParameter("existingServiceBusResourceGroup");
var serviceBus = builder.AddAzureServiceBus("messaging")
.AsExisting(existingServiceBusName, existingServiceBusResourceGroup);
builder.AddProject<Projects.WebApplication>("web")
.WithReference(serviceBus);
// After adding all resources, run the app...
builder.Build().Run();

For more information on treating Azure resources as existing resources, see Use existing Azure resources.

To add a queue to an Azure Service Bus namespace, call AddServiceBusQueue (C#) or addServiceBusQueue (TypeScript) on the Service Bus resource builder:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging");
var queue = serviceBus.AddServiceBusQueue("queue");
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(queue);
// After adding all resources, run the app...
builder.Build().Run();

This expresses an explicit parent-child relationship between the messaging Service Bus namespace and its child queue. The queue is created in the namespace that the AzureServiceBusResource represents. For more information, see Queues, topics, and subscriptions in Azure Service Bus.

To add a topic, call AddServiceBusTopic (C#) or addServiceBusTopic (TypeScript) on the Service Bus resource builder:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging");
var topic = serviceBus.AddServiceBusTopic("topic");
// After adding all resources, run the app...
builder.Build().Run();

The topic is created in the namespace that the AzureServiceBusResource represents.

To add a subscription for a topic, call AddServiceBusSubscription (C#) or addServiceBusSubscription (TypeScript) on the topic resource builder:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging");
var topic = serviceBus.AddServiceBusTopic("topic");
topic.AddServiceBusSubscription("sub1");
// After adding all resources, run the app...
builder.Build().Run();

For more information, see Queues, topics, and subscriptions in Azure Service Bus.

In C# AppHosts, you can configure advanced subscription properties — such as maximum delivery count and correlation filter rules — using the WithProperties method:

C# — AppHost.cs
using Aspire.Hosting.Azure;
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging");
var topic = serviceBus.AddServiceBusTopic("topic");
topic.AddServiceBusSubscription("sub1")
.WithProperties(subscription =>
{
subscription.MaxDeliveryCount = 10;
subscription.Rules.Add(
new AzureServiceBusRule("app-prop-filter-1")
{
CorrelationFilter = new()
{
ContentType = "application/text",
CorrelationId = "id1",
Subject = "subject1",
MessageId = "msgid1",
ReplyTo = "someQueue",
ReplyToSessionId = "sessionId",
SessionId = "session1",
SendTo = "xyz"
}
});
});
// After adding all resources, run the app...
builder.Build().Run();

For local development, Aspire can run the Azure Service Bus Emulator as a container. Chain a call to RunAsEmulator (C#) or runAsEmulator (TypeScript) on the Service Bus resource builder:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging")
.RunAsEmulator();
// After adding all resources, run the app...
builder.Build().Run();

When you call runAsEmulator, Aspire provisions the mcr.microsoft.com/azure-messaging/servicebus-emulator container and its companion mcr.microsoft.com/azure-sql-edge container locally. The emulator starts alongside your AppHost instead of requiring an Azure subscription. For more information, see Container resource lifecycle.

By default, the Service Bus emulator container exposes the following endpoints:

EndpointImageContainer portHost port
emulatormcr.microsoft.com/azure-messaging/servicebus-emulator5672dynamic
tcpmcr.microsoft.com/mssql/server1433dynamic

By default, the host port is assigned dynamically. To pin it to a specific port, pass the configureContainer callback and call withHostPort:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging")
.RunAsEmulator(emulator =>
{
emulator.WithHostPort(7777);
});
// After adding all resources, run the app...
builder.Build().Run();

The preceding code maps the emulator endpoint to host port 7777:

Endpoint namePort mapping (container:host)
emulator5672:7777

Configure the emulator with a custom JSON file

Section titled “Configure the emulator with a custom JSON file”

The Service Bus emulator generates its configuration automatically from the resources you’ve added. To provide a fully custom configuration file instead, call WithConfigurationFile (C#) or withConfigurationFile (TypeScript):

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging")
.RunAsEmulator(emulator =>
{
emulator.WithConfigurationFile(
path: "./messaging/custom-config.json");
});
// After adding all resources, run the app...
builder.Build().Run();

Patch the emulator configuration with WithConfiguration

Section titled “Patch the emulator configuration with WithConfiguration”

In C# AppHosts, you can also update specific properties in the auto-generated configuration using a JsonNode callback, without replacing the entire file:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var serviceBus = builder.AddAzureServiceBus("messaging")
.RunAsEmulator(emulator =>
{
emulator.WithConfiguration(
(JsonNode configuration) =>
{
var userConfig = configuration["UserConfig"];
var ns = userConfig["Namespaces"][0];
var firstQueue = ns["Queues"][0];
var properties = firstQueue["Properties"];
properties["MaxDeliveryCount"] = 5;
properties["RequiresDuplicateDetection"] = true;
properties["DefaultMessageTimeToLive"] = "PT2H";
});
});
// After adding all resources, run the app...
builder.Build().Run();

If you’re new to Bicep, it’s a domain-specific language for defining Azure resources. With Aspire, you don’t need to write Bicep by hand — the provisioning APIs generate it for you. When you publish your app, the generated Bicep is output alongside the manifest file. When you add an Azure Service Bus resource, the following Bicep is generated:

Generated Bicep — service-bus.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
param sku string = 'Standard'
resource service_bus 'Microsoft.ServiceBus/namespaces@2024-01-01' = {
name: take('servicebus-${uniqueString(resourceGroup().id)}', 50)
location: location
properties: {
disableLocalAuth: true
}
sku: {
name: sku
}
tags: {
'aspire-resource-name': 'service-bus'
}
}
output serviceBusEndpoint string = service_bus.properties.serviceBusEndpoint
output name string = service_bus.name

In addition to the namespace, Aspire generates a roles module that assigns the Azure Service Bus Data Owner built-in role to the app’s managed identity:

Generated Bicep — service-bus-roles.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
param service_bus_outputs_name string
param principalType string
param principalId string
resource service_bus 'Microsoft.ServiceBus/namespaces@2024-01-01' existing = {
name: service_bus_outputs_name
}
resource service_bus_AzureServiceBusDataOwner 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(service_bus.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '090c5cfd-751d-490a-894a-3ce6f1109419'))
properties: {
principalId: principalId
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '090c5cfd-751d-490a-894a-3ce6f1109419')
principalType: principalType
}
scope: service_bus
}

For more information on the assigned role, see Azure Service Bus Data Owner.

All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables customization of the generated Bicep using the fluent ConfigureInfrastructure API. For example, you can configure the SKU, location, tags, and more:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureServiceBus("service-bus")
.ConfigureInfrastructure(infra =>
{
var serviceBusNamespace = infra.GetProvisionableResources()
.OfType<ServiceBusNamespace>()
.Single();
serviceBusNamespace.Sku = new ServiceBusSku
{
Name = ServiceBusSkuName.Premium
};
serviceBusNamespace.Tags.Add("ExampleKey", "Example value");
});
// After adding all resources, run the app...
builder.Build().Run();

The Azure Service Bus hosting integration automatically adds a health check for the Service Bus resource. The health check verifies that the Service Bus is running and that a connection can be established.

The hosting integration relies on the 📦 AspNetCore.HealthChecks.AzureServiceBus NuGet package.