10

So according to StackExchange.Redis docs, I am to re-use IConnectionMultiplexer.

services.AddSingleton<IConnectionMultiplexer>(
        ConnectionMultiplexer
              .Connect($"{configsOptions.RedisUrl},password={secretsOptions.RedisPassword}"));

But then I found that in my redis service method, I'd have to inject the IConnectionMultiplexer and then connect to the database like this:

public Task GetSomethingFromRedis(string key)
{
    IDatabase db = connectionMultiplexer.GetDatabase();
    string value = db.StringGet(key);
}

Instead of calling connectionMultiplexer.GetDatabase() every time, is OK for me to have a Singleton of the IDatabase object, injected like this? Or is this a really bad idea?

services.AddSingleton<IDatabase>(cfg =>
   {
         var redisConnection = 
         ConnectionMultiplexer
            .Connect($"{configsOptions.RedisUrl},password={secretsOptions.RedisPassword}");

         return redisConnection.GetDatabase();
   });
2
  • 1
    "he object returned from GetDatabase is a cheap pass-thru object, and does not need to be stored." so it seems like something that you would create every time no? Commented Aug 5, 2021 at 20:42
  • 1
    Also: stackoverflow.com/a/40849257/4122889 Commented Aug 5, 2021 at 20:43

1 Answer 1

9

I ended up doing this

services.AddScoped<IDatabase>(cfg =>
     {
         IConnectionMultiplexer multiplexer = ConnectionMultiplexer.Connect($"{configsOptions.RedisUrl},password={secretsOptions.RedisPassword}");
         return multiplexer.GetDatabase();
     });

And then in my service:

private readonly IDatabase cache;

public RedisService(IDatabase cache)
{
   this.cache = cache;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works, full stop. But the docs state The object returned from GetDatabase is a cheap pass-thru object, and does not need to be stored. This means you can use AddScoped<IConnectionMultiplexer> and simply return the created ConnectionMultiplexer. And maybe it's even better to instantiate it as a singleton per these docs: 'Because the ConnectionMultiplexer does a lot, it is designed to be shared and reused between callers. You should not create a ConnectionMultiplexer per operation.' Source: stackexchange.github.io/StackExchange.Redis/Basics

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.