4

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 2

3

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);
            };
        });
Sign up to request clarification or add additional context in comments.

1 Comment

will services.BuildServiceProvider() combined with builder.build not create a duplicate of the singleton?
2

Wy not like this?

        IConnectionMultiplexer? connectionMultiplexer = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("LockExchange"));
        services.AddSingleton(connectionMultiplexer);
        services.AddStackExchangeRedisCache(options =>
        {
            options.ConnectionMultiplexerFactory = () => Task.FromResult(connectionMultiplexer);
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.