Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 735
pampua84 Avatar asked Aug 30 '25 18:08

pampua84


2 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);
            };
        });
like image 188
Firdaus Kamaruddin Avatar answered Sep 02 '25 07:09

Firdaus Kamaruddin


Wy not like this?

        IConnectionMultiplexer? connectionMultiplexer = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("LockExchange"));
        services.AddSingleton(connectionMultiplexer);
        services.AddStackExchangeRedisCache(options =>
        {
            options.ConnectionMultiplexerFactory = () => Task.FromResult(connectionMultiplexer);
        });
like image 45
knakkert Avatar answered Sep 02 '25 06:09

knakkert