C# Asp.Net Core Use Redis for IDistributedMemoryCache and DataProtection

Viewed 442

as the title suggests I should use Redis both as DistributedCache and to store the key for the DataProtection, the problem is that I don't know if it is correct to register the Redis instance twice, like this:

public void ConfigureServices(IServiceCollection services)
{
    //......

    // First Instance of Redis
    serviceCollection.AddStackExchangeRedisCache(options =>
    {
        options.ConfigurationOptions = new ConfigurationOptions();
        options.ConfigurationOptions.EndPoints.Add("127.0.0.1", 6379);
        options.ConfigurationOptions.Password = "*********";
        options.ConfigurationOptions.ConnectRetry = 5;
    });

    // Second Instance of Redis
    var redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");
    serviceCollection.AddDataProtection()
        .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");

    //......
}

or it is possible to share the same instance already registered in the first method?
In case it is possible to come to do? Thanks

1 Answers

in .NET 6, microsoft have added new option when configuring redis to allow get or set delegate to create ConnectionMultiplexer, below is naive example

ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("server1:6729");
services.AddSingleton<IConnectionMultiplexer>(cm);

services.AddStackExchangeRedisCache(options =>
        {
            options.ConnectionMultiplexerFactory = () =>
            {
                var serviceProvider = services.BuildServiceProvider();
                IConnectionMultiplexer connection = serviceProvider.GetService<IConnectionMultiplexer>();
                return Task.FromResult(connection);
            };
        });
Related