Azure Web PubSub integration
Цей контент ще не доступний вашою мовою.
Azure Web PubSub is a fully managed real-time messaging service that enables you to build real-time web applications using WebSockets and publish-subscribe patterns. The Aspire Azure Web PubSub integration enables you to connect to Azure Web PubSub instances from your applications.
Hosting integration
Section titled “Hosting integration”The Aspire Azure Web PubSub hosting integration models the Web PubSub resources as the following types:
AzureWebPubSubResource: Represents an Azure Web PubSub resource, including connection information to the underlying Azure resource.AzureWebPubSubHubResource: Represents a Web PubSub hub settings resource, which contains the settings for a hub. For example, you can specify if the hub allows anonymous connections or add event handlers to the hub.
To access these types and APIs for expressing them within your AppHost project, install the 📦 Aspire.Hosting.Azure.WebPubSub NuGet package:
aspire add azure-webpubsubAspire CLI інтерактивний; оберіть відповідний результат пошуку:
Select an integration to add:
> azure-webpubsub (Aspire.Hosting.Azure.WebPubSub)> Other results listed as selectable options...#:package Aspire.Hosting.Azure.WebPubSub@*<PackageReference Include="Aspire.Hosting.Azure.WebPubSub" Version="*" />Add an Azure Web PubSub resource
Section titled “Add an Azure Web PubSub resource”To add an Azure Web PubSub resource to your AppHost project, call the AddAzureWebPubSub method providing a name:
var builder = DistributedApplication.CreateBuilder(args);
var webPubSub = builder.AddAzureWebPubSub("web-pubsub");
builder.AddProject<Projects.ExampleProject>() .WithReference(webPubSub);
// After adding all resources, run the app...The preceding code adds an Azure Web PubSub resource named web-pubsub to the AppHost project. The WithReference method passes the connection information to the ExampleProject project.
Add an Azure Web PubSub hub resource
Section titled “Add an Azure Web PubSub hub resource”When you add an Azure Web PubSub resource, you can also add a child hub resource. The hub resource is a logical grouping of connections and event handlers. To add an Azure Web PubSub hub resource to your AppHost project, chain a call to the AddHub method:
var builder = DistributedApplication.CreateBuilder(args);
var worker = builder.AddProject<Projects.WorkerService>("worker") .WithExternalHttpEndpoints();
var webPubSub = builder.AddAzureWebPubSub("web-pubsub");var messagesHub = webPubSub.AddHub(name: "messages", hubName: "messageHub");
// After adding all resources, run the app...The preceding code adds an Azure Web PubSub hub resource named messages and a hub name of messageHub, which enables the addition of event handlers. To add an event handler, call the AddEventHandler:
var builder = DistributedApplication.CreateBuilder(args);
var worker = builder.AddProject<Projects.WorkerService>("worker") .WithExternalHttpEndpoints();
var webPubSub = builder.AddAzureWebPubSub("web-pubsub");var messagesHub = webPubSub.AddHub(name: "messages", hubName: "messageHub");
messagesHub.AddEventHandler( $"{worker.GetEndpoint("https")}/eventhandler/", systemEvents: ["connected"]);
// After adding all resources, run the app...The preceding code adds a worker service project named worker with an external HTTP endpoint. The hub named messages resource is added to the web-pubsub resource, and an event handler is added to the messagesHub resource. The event handler URL is set to the worker service’s external HTTP endpoint. For more information, see Azure Web PubSub event handlers.
Connect to an existing Azure Web PubSub instance
Section titled “Connect to an existing Azure Web PubSub instance”You might have an existing Azure Web PubSub service that you want to connect to. You can chain a call to annotate that your AzureWebPubSubResource is an existing resource:
var builder = DistributedApplication.CreateBuilder(args);
var existingPubSubName = builder.AddParameter("existingPubSubName");var existingPubSubResourceGroup = builder.AddParameter("existingPubSubResourceGroup");
var webPubSub = builder.AddAzureWebPubSub("web-pubsub") .AsExisting(existingPubSubName, existingPubSubResourceGroup);
builder.AddProject<Projects.ExampleProject>() .WithReference(webPubSub);
// After adding all resources, run the app...For more information on treating Azure Web PubSub resources as existing resources, see Use existing Azure resources.
Provisioning-generated Bicep
Section titled “Provisioning-generated Bicep”When you publish your app, Aspire provisioning APIs generate Bicep alongside the manifest file. Bicep is a domain-specific language for defining Azure resources. For more information, see Bicep Overview.
When you add an Azure Web PubSub resource, the following Bicep is generated:
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
param sku string = 'Free_F1'
param capacity int = 1
param messages_url_0 string
resource web_pubsub 'Microsoft.SignalRService/webPubSub@2024-03-01' = { name: take('webpubsub-${uniqueString(resourceGroup().id)}', 63) location: location properties: { disableLocalAuth: true } sku: { name: sku capacity: capacity } tags: { 'aspire-resource-name': 'web-pubsub' }}
resource messages 'Microsoft.SignalRService/webPubSub/hubs@2024-03-01' = { name: 'messages' properties: { eventHandlers: [ { urlTemplate: messages_url_0 userEventPattern: '*' systemEvents: [ 'connected' ] } ] } parent: web_pubsub}
output endpoint string = 'https://${web_pubsub.properties.hostName}'
output name string = web_pubsub.nameThe preceding Bicep is a module that provisions an Azure Web PubSub resource. Additionally, role assignments are created for the Azure resource in a separate module:
@description('The location for the resource(s) to be deployed.')param location string = resourceGroup().location
param web_pubsub_outputs_name string
param principalType string
param principalId string
resource web_pubsub 'Microsoft.SignalRService/webPubSub@2024-03-01' existing = { name: web_pubsub_outputs_name}
resource web_pubsub_WebPubSubServiceOwner 'Microsoft.Authorization/roleAssignments@2022-04-01' = { name: guid(web_pubsub.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '12cf5a90-567b-43ae-8102-96cf46c7d9b4')) properties: { principalId: principalId roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '12cf5a90-567b-43ae-8102-96cf46c7d9b4') principalType: principalType } scope: web_pubsub}The generated Bicep is a starting point and is influenced by changes to the provisioning infrastructure in C#. Customizations to the Bicep file directly will be overwritten, so make changes through the C# provisioning APIs to ensure they are reflected in the generated files.
Customize provisioning infrastructure
Section titled “Customize provisioning infrastructure”All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables the customization of the generated Bicep by providing a fluent API to configure the Azure resources using the ConfigureInfrastructure API:
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureWebPubSub("web-pubsub") .ConfigureInfrastructure(infra => { var webPubSubService = infra.GetProvisionableResources() .OfType<WebPubSubService>() .Single();
webPubSubService.Sku.Name = "Standard_S1"; webPubSubService.Sku.Capacity = 5; webPubSubService.Tags.Add("ExampleKey", "Example value"); });The preceding code:
- Chains a call to the
ConfigureInfrastructureAPI:- The
infraparameter is an instance of theAzureResourceInfrastructuretype. - The provisionable resources are retrieved by calling the
GetProvisionableResourcesmethod. - The single
WebPubSubServiceresource is retrieved. - The
Skuobject has its name and capacity properties set toStandard_S1and5, respectively. - A tag is added to the Web PubSub resource with a key of
ExampleKeyand a value ofExample value.
- The
There are many more configuration options available to customize the Web PubSub resource. For more information, see Azure.Provisioning customization.
Client integration
Section titled “Client integration”The Aspire Azure Web PubSub client integration is used to connect to an Azure Web PubSub service using the WebPubSubServiceClient. To get started with the Aspire Azure Web PubSub service client integration, install the 📦 Aspire.Azure.Messaging.WebPubSub NuGet package.
dotnet add package Aspire.Azure.Messaging.WebPubSub#:package Aspire.Azure.Messaging.WebPubSub@*<PackageReference Include="Aspire.Azure.Messaging.WebPubSub" Version="*" />Supported Web PubSub client types
Section titled “Supported Web PubSub client types”The following Web PubSub client types are supported by the library:
| Azure client type | Azure options class | Aspire settings class |
|---|---|---|
WebPubSubServiceClient | WebPubSubServiceClientOptions | AzureMessagingWebPubSubSettings |
Add Web PubSub client
Section titled “Add Web PubSub client”In the Program.cs file of your client-consuming project, call the AddAzureWebPubSubServiceClient extension method to register a WebPubSubServiceClient for use via the dependency injection container. The method takes a connection name parameter:
builder.AddAzureWebPubSubServiceClient(connectionName: "web-pubsub");After adding the WebPubSubServiceClient, you can retrieve the client instance using dependency injection:
public class ExampleService(WebPubSubServiceClient client){ // Use client...}For more information, see:
- Azure.Messaging.WebPubSub documentation for examples on using the
WebPubSubServiceClient. - Dependency injection in .NET for details on dependency injection.
Add keyed Web PubSub client
Section titled “Add keyed Web PubSub client”There might be situations where you want to register multiple WebPubSubServiceClient instances with different connection names. To register keyed Web PubSub clients, call the AddKeyedAzureWebPubSubServiceClient method:
builder.AddKeyedAzureWebPubSubServiceClient(name: "messages");builder.AddKeyedAzureWebPubSubServiceClient(name: "commands");Then you can retrieve the client instances using dependency injection:
public class ExampleService( [KeyedService("messages")] WebPubSubServiceClient messagesClient, [KeyedService("commands")] WebPubSubServiceClient commandsClient){ // Use clients...}For more information, see Keyed services in .NET.
Configuration
Section titled “Configuration”The Aspire Azure Web PubSub library provides multiple options to configure the Azure Web PubSub connection based on the requirements and conventions of your project. Either an Endpoint or a ConnectionString must be supplied.
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 AddAzureWebPubSubServiceClient:
builder.AddAzureWebPubSubServiceClient( "web-pubsub", settings => settings.HubName = "your_hub_name");The connection information is retrieved from the ConnectionStrings configuration section. Two connection formats are supported:
-
Service endpoint (recommended): Uses the service endpoint with
DefaultAzureCredential.{"ConnectionStrings": {"web-pubsub": "https://{account_name}.webpubsub.azure.com"}} -
Connection string: Includes an access key.
{"ConnectionStrings": {"web-pubsub": "Endpoint=https://{account_name}.webpubsub.azure.com;AccessKey={account_key}"}}
Use configuration providers
Section titled “Use configuration providers”The library supports Microsoft.Extensions.Configuration. It loads settings from configuration using the Aspire:Azure:Messaging:WebPubSub key:
{ "Aspire": { "Azure": { "Messaging": { "WebPubSub": { "DisableHealthChecks": true, "HubName": "your_hub_name" } } } }}Use inline delegates
Section titled “Use inline delegates”You can configure settings inline:
builder.AddAzureWebPubSubServiceClient( "web-pubsub", settings => settings.DisableHealthChecks = true);Observability and telemetry
Section titled “Observability and telemetry”Aspire integrations automatically set up Logging, Tracing, and Metrics configurations.
Logging
Section titled “Logging”The Aspire Azure Web PubSub integration uses the following log categories:
AzureAzure.CoreAzure.IdentityAzure.Messaging.WebPubSub
Tracing
Section titled “Tracing”The Aspire Azure Web PubSub integration will emit the following tracing activities using OpenTelemetry:
Azure.Messaging.WebPubSub.*
Metrics
Section titled “Metrics”The Aspire Azure Web PubSub integration currently doesn’t support metrics by default due to limitations with the Azure SDK for .NET.