StackExchange.Redis IDatabase 的依赖注入?

StackExchange.Redis dependency injection of IDatabase?

所以according to StackExchange.Redis docs,我要重新使用IConnectionMultiplexer

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

但是后来我发现在我的redis服务方法中,我必须注入IConnectionMultiplexer然后像这样连接到数据库:

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

不用每次都调用 connectionMultiplexer.GetDatabase(),我可以像这样注入 IDatabase 对象的 Singleton 吗?或者这是一个非常糟糕的主意?

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

         return redisConnection.GetDatabase();
   });

我最后做了这个

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

然后在我的服务中:

private readonly IDatabase cache;

public RedisService(IDatabase cache)
{
   this.cache = cache;
}