.NET Aspire Azure Cache for Redis®* integration

Includes: Hosting integration and Client integration

Azure Cache for Redis provides an in-memory data store based on the Redis software. Redis improves the performance and scalability of an application that uses backend data stores heavily. It's able to process large volumes of application requests by keeping frequently accessed data in the server memory, which can be written to and read from quickly. Redis brings a critical low-latency and high-throughput data storage solution to modern applications.

Azure Cache for Redis offers both the Redis open-source (OSS Redis) and a commercial product from Redis Inc. (Redis Enterprise) as a managed service. It provides secure and dedicated Redis server instances and full Redis API compatibility. Microsoft operates the service, hosted on Azure, and usable by any application within or outside of Azure.

The .NET Aspire Azure Cache for Redis integration enables you to connect to existing Azure Cache for Redis instances, or create new instances, or run as a container locally from .NET with the docker.io/library/redis container image.

Hosting integration

The .NET Aspire Azure Cache for Redis hosting integration models an Azure Redis resource as the AzureRedisCacheResource type. To access this type and APIs for expressing them as resources in your app host project, add the 📦 Aspire.Hosting.Azure.Redis NuGet package:

dotnet add package Aspire.Hosting.Azure.Redis

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

Add Azure Cache for Redis resource

In your app host project, call AddAzureRedis on the builder instance to add an Azure Cache for Redis resource, as shown in the following example:

var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddAzureRedis("azcache");

builder.AddProject<Projects.ExampleProject>()
       .WithReference(cache);

// After adding all resources, run the app...

The preceding call to AddAzureRedis configures the Redis server resource to be deployed as an Azure Cache for Redis.

Important

By default, AddAzureRedis configures Microsoft Entra ID authentication. This requires changes to applications that need to connect to these resources, for example, client integrations.

Tip

When you call AddAzureRedis, it implicitly calls AddAzureProvisioning—which adds support for generating Azure resources dynamically during app startup. The app must configure the appropriate subscription and location. For more information, see Local provisioning: Configuration.

Generated provisioning Bicep

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


Toggle Azure Cache for Redis Bicep.

@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location

param principalId string

param principalName string

resource redis 'Microsoft.Cache/redis@2024-03-01' = {
  name: take('redis-${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': 'redis'
  }
}

resource redis_contributor 'Microsoft.Cache/redis/accessPolicyAssignments@2024-03-01' = {
  name: take('rediscontributor${uniqueString(resourceGroup().id)}', 24)
  properties: {
    accessPolicyName: 'Data Contributor'
    objectId: principalId
    objectIdAlias: principalName
  }
  parent: redis
}

output connectionString string = '${redis.properties.hostName},ssl=true'

The preceding Bicep is a module that provisions an Azure Cache for Redis with the following defaults:

  • location: The location of the Azure Cache for Redis resource. The default is the location of the resource group.
  • principalId: The principal ID of the Azure Cache for Redis resource.
  • principalName: The principal name of the Azure Cache for Redis resource.
  • sku: The SKU of the Azure Cache for Redis resource. The default is Basic with a capacity of 1.
  • enableNonSslPort: The non-SSL port of the Azure Cache for Redis resource. The default is false.
  • disableAccessKeyAuthentication: The access key authentication of the Azure Cache for Redis resource. The default is true.
  • minimumTlsVersion: The minimum TLS version of the Azure Cache for Redis resource. The default is 1.2.
  • redisConfiguration: The Redis configuration of the Azure Cache for Redis resource. The default is aad-enabled set to true.
  • tags: The tags of the Azure Cache for Redis resource. The default is aspire-resource-name set to the name of the Aspire resource, in this case redis.
  • redis_contributor: The contributor of the Azure Cache for Redis resource, with an access policy name of Data Contributor.
  • connectionString: The connection string of the Azure Cache for Redis resource.

In addition to the Azure Cache for Redis, it also provisions an access policy assignment to the application access to the cache. The generated Bicep is a starting point and can be customized to meet your specific requirements.

Customize provisioning infrastructure

All .NET 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<T>(IResourceBuilder<T>, Action<AzureResourceInfrastructure>) API. For example, you can configure the kind, consistencyPolicy, locations, and more. The following example demonstrates how to customize the Azure Cache for Redis resource:

builder.AddAzureRedis("redis")
    .WithAccessKeyAuthentication()
    .ConfigureInfrastructure(infra =>
    {
        var redis = infra.GetProvisionableResources()
                         .OfType<RedisResource>()
                         .Single();

        redis.Sku = new()
        {
            Family = RedisSkuFamily.BasicOrStandard,
            Name = RedisSkuName.Standard,
            Capacity = 1,                    
        };
        redis.Tags.Add("ExampleKey", "Example value");
    });

The preceding code:

There are many more configuration options available to customize the Azure Cache for Redis resource. For more information, see Azure.Provisioning.Redis. For more information, see Azure.Provisioning customization.

Connect to an existing Azure Cache for Redis

You might have an existing Azure Cache for Redis that you want to connect to. Instead of representing a new Azure Cache for Redis resource, you can add a connection string to the app host. To add a connection to an existing Azure Cache for Redis, call the AddConnectionString method:

var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddConnectionString("azure-redis");

builder.AddProject<Projects.WebApplication>("web")
       .WithReference(cache);

// After adding all resources, run the app...

Note

Connection strings are used to represent a wide range of connection information, including database connections, message brokers, endpoint URIs, and other services. In .NET Aspire nomenclature, the term "connection string" is used to represent any kind of connection information.

The connection string is configured in the app host's configuration, typically under User Secrets, under the ConnectionStrings section. The app host injects this connection string as an environment variable into all dependent resources, for example:

{
    "ConnectionStrings": {
        "azure-redis": "<your-redis-name>.redis.cache.windows.net:6380,ssl=true,abortConnect=False"
    }
}

The dependent resource can access the injected connection string by calling the GetConnectionString method, and passing the connection name as the parameter, in this case "azure-redis". The GetConnectionString API is shorthand for IConfiguration.GetSection("ConnectionStrings")[name].

Run Azure Cache for Redis resource as a container

The Azure Cache for Redis hosting integration supports running the Redis server as a local container. This is beneficial for situations where you want to run the Redis server locally for development and testing purposes, avoiding the need to provision an Azure resource or connect to an existing Azure Cache for Redis server.

To make use of the docker.io/library/redis container image, and run the Azure Cache for Redis instance as a container locally, chain a call to RunAsContainer, as shown in the following example:

var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddAzureRedis("azcache")
                   .RunAsContainer();

builder.AddProject<Projects.ExampleProject>()
       .WithReference(cache);

// After adding all resources, run the app...

The preceding code configures the Redis resource to run locally in a container.

Tip

The RunAsContainer method is useful for local development and testing. The API exposes an optional delegate that enables you to customize the underlying RedisResource configuration, such adding Redis Insights, Redis Commander, adding a data volume or data bind mount. For more information, see the .NET Aspire Redis hosting integration.

Configure the Azure Cache for Redis resource to use access key authentication

By default, the Azure Cache for Redis resource is configured to use Microsoft Entra ID authentication. If you want to use password authentication (not recommended), you can configure the server to use password authentication by calling the WithAccessKeyAuthentication method:

var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddAzureRedis("azcache")
                   .WithAccessKeyAuthentication();

builder.AddProject<Projects.ExampleProject>()
       .WithReference(cache);

// After adding all resources, run the app...

The preceding code configures the Azure Cache for Redis resource to use access key authentication. This alters the generated Bicep to use access key authentication instead of Microsoft Entra ID authentication. In other words, the connection string will contain a password, and will be added to an Azure Key Vault secret.

Client integration

To get started with the .NET Aspire Stack Exchange Redis client integration, install the 📦 Aspire.StackExchange.Redis NuGet package in the client-consuming project, that is, the project for the application that uses the Redis client. The Redis client integration registers an IConnectionMultiplexer instance that you can use to interact with Redis.

dotnet add package Aspire.StackExchange.Redis

Add Redis client

In the Program.cs file of your client-consuming project, call the AddRedisClient extension method on any IHostApplicationBuilder to register an IConnectionMultiplexer for use via the dependency injection container. The method takes a connection name parameter.

builder.AddRedisClient(connectionName: "cache");

Tip

The connectionName parameter must match the name used when adding the Azure Cache for Redis resource in the app host project. For more information, see Add Azure Cache for Redis resource.

You can then retrieve the IConnectionMultiplexer instance using dependency injection. For example, to retrieve the connection from an example service:

public class ExampleService(IConnectionMultiplexer connectionMux)
{
    // Use connection multiplexer...
}

For more information on dependency injection, see .NET dependency injection.

Add Azure Cache for Redis authenticated client

By default, when you call AddAzureRedis in your Redis hosting integration, it configures Microsoft Entra ID. Install the 📦 Microsoft.Azure.StackExchangeRedis NuGet package to enable authentication:

dotnet add package Microsoft.Azure.StackExchangeRedis

The Redis connection can be consumed using the client integration and Microsoft.Azure.StackExchangeRedis. Consider the following configuration code:

var azureOptionsProvider = new AzureOptionsProvider();

var configurationOptions = ConfigurationOptions.Parse(
    builder.Configuration.GetConnectionString("cache") ?? 
    throw new InvalidOperationException("Could not find a 'cache' connection string."));

if (configurationOptions.EndPoints.Any(azureOptionsProvider.IsMatch))
{
    await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(
        new DefaultAzureCredential());
}

builder.AddRedisClient("cache", configureOptions: options =>
{
    options.Defaults = configurationOptions.Defaults;
});

For more information, see the Microsoft.Azure.StackExchangeRedis repo.

Add keyed Redis client

There might be situations where you want to register multiple IConnectionMultiplexer instances with different connection names. To register keyed Redis clients, call the AddKeyedRedisClient method:

builder.AddKeyedRedisClient(name: "chat");
builder.AddKeyedRedisClient(name: "queue");

Then you can retrieve the IConnectionMultiplexer instances using dependency injection. For example, to retrieve the connection from an example service:

public class ExampleService(
    [FromKeyedServices("chat")] IConnectionMultiplexer chatConnectionMux,
    [FromKeyedServices("queue")] IConnectionMultiplexer queueConnectionMux)
{
    // Use connections...
}

For more information on keyed services, see .NET dependency injection: Keyed services.

Configuration

The .NET Aspire Stack Exchange Redis client integration provides multiple options to configure the Redis connection based on the requirements and conventions of your project.

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 AddRedis:

builder.AddRedis("cache");

Then the connection string will be retrieved from the ConnectionStrings configuration section:

{
  "ConnectionStrings": {
    "cache": "localhost:6379"
  }
}

For more information on how to format this connection string, see the Stack Exchange Redis configuration docs.

Use configuration providers

The .NET Aspire Stack Exchange Redis integration supports Microsoft.Extensions.Configuration. It loads the StackExchangeRedisSettings from configuration by using the Aspire:StackExchange:Redis key. Example appsettings.json that configures some of the options:

{
  "Aspire": {
    "StackExchange": {
      "Redis": {
        "ConfigurationOptions": {
          "ConnectTimeout": 3000,
          "ConnectRetry": 2
        },
        "DisableHealthChecks": true,
        "DisableTracing": false
      }
    }
  }
}

For the complete Redis client integration JSON schema, see Aspire.StackExchange.Redis/ConfigurationSchema.json.

Use inline delegates

You can also pass the Action<StackExchangeRedisSettings> delegate to set up some or all the options inline, for example to configure DisableTracing:

builder.AddRedisClient(
    "cache",
    static settings => settings.DisableTracing = true);

Client integration health checks

By default, .NET Aspire client integrations have health checks enabled for all services. Similarly, many .NET Aspire hosting integrations also enable health check endpoints. For more information, see:

The .NET Aspire Stack Exchange Redis integration handles the following:

  • Adds the health check when StackExchangeRedisSettings.DisableHealthChecks is false, which attempts to connect to the container instance.
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic.

Observability and telemetry

.NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. 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

The .NET Aspire Stack Exchange Redis integration uses the following log categories:

  • Aspire.StackExchange.Redis

Tracing

The .NET Aspire Stack Exchange Redis integration will emit the following tracing activities using OpenTelemetry:

  • OpenTelemetry.Instrumentation.StackExchangeRedis

Metrics

The .NET Aspire Stack Exchange Redis integration currently doesn't support metrics by default due to limitations with the StackExchange.Redis library.

See also

*: Redis is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Any use by Microsoft is for referential purposes only and does not indicate any sponsorship, endorsement or affiliation between Redis and Microsoft. Return to top?