Zum Inhalt springen
Docs Try Aspire
Docs Try

Set up Azure Cache for Redis in the AppHost

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

Azure Cache for Redis logo

This article is the reference for the Aspire Azure Cache for Redis Hosting integration. It enumerates the AppHost APIs — with examples for both AppHost.cs and apphost.ts — that you use to model an Azure managed Redis cache resource in your AppHost project.

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

To start building an Aspire app that uses Azure Cache for Redis, install the 📦 Aspire.Hosting.Azure.Redis NuGet package:

Terminal
aspire add azure-redis

Learn more about aspire add in the command reference.

Or, choose a manual installation approach:

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

Once you’ve installed the hosting integration in your AppHost project, you can add an Azure Managed Redis resource as shown in the following examples:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddAzureManagedRedis("cache");
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(cache);
// After adding all resources, run the app...
builder.Build().Run();
  1. The resource is named cache and represents an Azure Managed Redis cache. Aspire generates the Bicep needed to provision it in Azure.

  2. By default, Aspire configures the resource to use Microsoft Entra ID (role-based access) authentication. No password is stored in the connection string. For more information, see Configure access key authentication.

  3. The WithReference (or withReference) call configures a connection in the consuming project named after the resource, such as cache in the preceding example.

The Azure Cache for Redis hosting integration supports running a local Redis container during development. This lets you develop and test your app locally without provisioning an Azure resource or connecting to an existing Azure Cache for Redis instance.

To run the resource as a container, chain a call to RunAsContainer (or runAsContainer):

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

The preceding code pulls the docker.io/library/redis container image and runs it locally. The consuming app connects to the container using a password-based connection string during development.

Connect to an existing Azure Cache for Redis instance

Section titled “Connect to an existing Azure Cache for Redis instance”

If you already have an Azure Cache for Redis instance you want to use, call AsExisting (or asExisting) to annotate that the resource already exists rather than being provisioned:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var existingRedisName = builder.AddParameter("existingRedisName");
var existingRedisResourceGroup = builder.AddParameter("existingRedisResourceGroup");
var cache = builder.AddAzureManagedRedis("cache")
.AsExisting(existingRedisName, existingRedisResourceGroup);
builder.AddProject<Projects.ExampleProject>("apiservice")
.WithReference(cache);
// 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.

By default, the Azure Managed Redis resource uses Microsoft Entra ID authentication. To switch to access key authentication (not recommended for production), call WithAccessKeyAuthentication (or withAccessKeyAuthentication):

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

When access key authentication is enabled, the generated Bicep stores the access key in an Azure Key Vault secret and injects it as the Password connection property. The connection string includes the password instead of relying on a managed identity token.

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 Managed Redis resource, the following Bicep is generated:

Bicep — cache.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
resource cache 'Microsoft.Cache/redis@2024-11-01' = {
name: take('cache-${uniqueString(resourceGroup().id)}', 63)
location: location
properties: {
sku: {
name: 'Basic'
family: 'C'
capacity: 1
}
enableNonSslPort: false
disableAccessKeyAuthentication: true
minimumTlsVersion: '1.2'
redisConfiguration: {
'aad-enabled': 'true'
}
}
tags: {
'aspire-resource-name': 'cache'
}
}
output connectionString string = '${cache.properties.hostName},ssl=true'
output name string = cache.name

In addition, role assignments are created for the Azure resource in a separate module:

Bicep — cache-roles.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
param cache_outputs_name string
param principalId string
param principalName string
resource cache 'Microsoft.Cache/redis@2024-11-01' existing = {
name: cache_outputs_name
}
resource cache_contributor 'Microsoft.Cache/redis/accessPolicyAssignments@2024-11-01' = {
name: guid(cache.id, principalId, 'Data Contributor')
properties: {
accessPolicyName: 'Data Contributor'
objectId: principalId
objectIdAlias: principalName
}
parent: cache
}

The generated Bicep provisions the Azure Cache for Redis instance and creates an access policy assignment so the consuming application can connect using its managed identity. The generated Bicep is a starting point that reflects the provisioning infrastructure configured in your AppHost. Customizations made directly to the Bicep files are overwritten on the next publish — make changes through the C# or TypeScript provisioning APIs instead.

All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables Bicep customization through the ConfigureInfrastructure API:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureManagedRedis("cache")
.ConfigureInfrastructure(infra =>
{
var redisCache = infra.GetProvisionableResources()
.OfType<RedisCache>()
.Single();
redisCache.Sku = new RedisSku
{
Name = RedisSkuName.Standard,
Family = RedisSkuFamily.C,
Capacity = 1,
};
redisCache.Tags.Add("ExampleKey", "Example value");
});
// After adding all resources, run the app...
builder.Build().Run();

The preceding C# code retrieves the RedisCache resource from the infrastructure and updates the SKU to Standard tier with capacity 1, then adds a tag. The TypeScript AppHost exposes the same configureInfrastructure API for adding Bicep parameters and customizing resource configuration.

For more configuration options, see Azure.Provisioning customization.

For the full reference of Azure Cache for Redis connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see Connect to Azure Cache for Redis.

The Azure Cache for Redis hosting integration automatically adds a health check for the resource when running as a local container. The health check verifies that the Redis instance is running and that a connection can be established.

The hosting integration relies on the 📦 AspNetCore.HealthChecks.Redis NuGet package to perform the health check.