.NET Aspire support for Azure SignalR Service

In this article, you learn how to use .NET Aspire to express an Azure SignalR Service resource. Demonstrating how to write a SignalR app is beyond the scope of this article. Instead, you explore an app that's already been written and how it's wired up with .NET Aspire. Like other Azure resources within the .NET Aspire app model, you benefit from simple provisioning and deployment with the Azure Developer CLI (azd). For more information, see Deploy a .NET Aspire project to Azure Container Apps using the azd (in-depth guide).

Hub host

The hub host project is where you host your SignalR hub, the project that calls AddSignalR() and MapHub for example.

Install the NuGet package

You need to install the 📦 Microsoft.Azure.SignalR NuGet package.

dotnet add package Microsoft.Azure.SignalR

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

Express the resource

Whichever project you're using to host your Hub is where you'll wire up your Azure SignalR Service resource. The following example demonstrates how to use the AddNamedAzureSignalR extension method which is chained on the AddSignalR method:

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();

builder.Services.AddProblemDetails();

builder.Services.AddSignalR()
                .AddNamedAzureSignalR("signalr");

var app = builder.Build();

app.UseExceptionHandler();

app.MapHub<ChatHub>(HubEndpoints.ChatHub);

app.MapDefaultEndpoints();

app.Run();

Calling AddNamedAzureSignalR adds Azure SignalR with the specified name, the connection string will be read from ConnectionStrings_{name}, the settings are loaded from Azure:SignalR:{name} section.

App host

In the app host project, you express an AzureSignalRResource with the AddAzureSignalR method. The following example demonstrates how the resource is referenced by the consuming project, in this case the Hub host project:

var builder = DistributedApplication.CreateBuilder(args);

var signalr = builder.ExecutionContext.IsPublishMode
    ? builder.AddAzureSignalR("signalr")
    : builder.AddConnectionString("signalr");

var apiService = builder.AddProject<Projects.SignalR_ApiService>("apiservice")
                        .WithReference(signalr);
  
builder.AddProject<Projects.SignalR_Web>("webfrontend")
       .WithReference(apiService);

builder.Build().Run();

In the preceding code:

  • The builder has its execution context checked to see if it's in publish mode.
  • When publishing the AddAzureSignalR method is called to express the AzureSignalRResource.
  • When not publishing, the AddConnectionString method is called to express an IResourceWithConnectionString to an existing resource.
  • The signalr resource is referenced by the Hub host project, in this case known as apiService.
  • The apiService project resource is referenced by the SignalR_Web project.

See also