skip to Main Content

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

2

Answers


  1. 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);
                };
            });
    
    Login or Signup to reply.
  2. Wy not like this?

            IConnectionMultiplexer? connectionMultiplexer = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("LockExchange"));
            services.AddSingleton(connectionMultiplexer);
            services.AddStackExchangeRedisCache(options =>
            {
                options.ConnectionMultiplexerFactory = () => Task.FromResult(connectionMultiplexer);
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search