Get started with the Redis Distributed Caching integration

Redis logo

The RedisĀ® distributed caching integration is used to register an IDistributedCache provider backed by a Redis server with the docker.io/library/redis container image.

In this introduction, you'll see how to install and use the Aspire Redis Distributed Caching integrations in a simple configuration. If you already have this knowledge, see Redis Distributed Caching hosting integration for full reference details.

Note

To follow this guide, you must have created an Aspire solution to work with. To learn how to do that, see Build your first Aspire app.

Set up hosting integration

To begin, install the Aspire Redis hosting integration in your Aspire AppHost project:

Install the NuGet package
dotnet add package Aspire.Hosting.Redis

Next, in the AppHost project, create instances of Redis resources and pass them to the consuming client projects:

var builder = DistributedApplication.CreateBuilder(args);
  
var cache = builder.AddRedis("cache");
  
var myService = builder.AddProject<Projects.ExampleProject>()
                       .WithReference(cache);
  
builder.Build().Run();

When Aspire adds a container image to the AppHost, it creates a new Redis instance on your local machine.

Tip

If you'd rather connect to an existing Redis instance, call AsExisting instead.

Set up client integration

To get started with the Redis distributed caching integration, install the package:

Install the NuGet package
dotnet add package Aspire.StackExchange.Redis.DistributedCaching

In the Program.cs file of your client-consuming project, call the AddRedisDistributedCache extension to register the required services for distributed caching:

builder.AddRedisDistributedCache(connectionName: "cache");

Tip

The connectionName parameter must match the name used when adding the Redis resource in the AppHost project.

You can then retrieve the IDistributedCache instance using dependency injection:

public class ExampleService(IDistributedCache cache)
{
    // Use cache...
}

See also

[!TIP] Registered trademark 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.