如何对键值对类使用依赖注入以使用Redis缓存

问题描述

这是我的代码:

public class RedisCache<TKey,TVal> : ICache<TKey,TVal> where TVal : class
{
        TimeSpan _defaultCacheDuration;
        Lazy<ConnectionMultiplexer> _connection;

        public RedisCache(string connectionString,TimeSpan defaultDuration)
        {
            if (defaultDuration <= TimeSpan.Zero)
                throw new ArgumentOutOfRangeException(nameof(defaultDuration),"Duration must be greater than zero");

            _connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(connectionString));

            _defaultCacheDuration = defaultDuration;
        }

        public async Task<TVal> GetAsync(TKey key)
        {
            var database = _connection.Value.GetDatabase();
            string keyString = key?.ToString() ?? "null";
            var result = await database.StringGetAsync(keyString);
            return result.IsNull ? null : GetObjectFromString(result);
        }
}

如何在startup.cs中注入它?

我尝试了这会引发编译时错误:
services.AddSingleton<ICache<>>(provider => new RedisCache<,>("myPrettyLocalhost:6379",new TimeSpan(1)));

有人可以帮我吗?

解决方法

在发布的代码中,您已将类型定义添加到缓存中,但实际上您仅在方法中使用它们,因此您的类应如下所示:

public class RedisCache {
    TimeSpan _defaultCacheDuration;
    Lazy<ConnectionMultiplexer> _connection;

    public RedisCache(string connectionString,TimeSpan defaultDuration) {
        if (defaultDuration <= TimeSpan.Zero)
            throw new ArgumentOutOfRangeException(nameof(defaultDuration),"Duration must be greater than zero");

        _connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(connectionString));

        _defaultCacheDuration = defaultDuration;
    }

    public async Task<TVal> GetAsync<TKey,TVal>(TKey key) where TVal : class {
        var database = _connection.Value.GetDatabase();
        string keyString = key?.ToString() ?? "null";
        var result = await database.StringGetAsync(keyString);
        return result.IsNull ? null : GetObjectFromString(result);
    }
}

这使得注入变得简单:

services.AddSingleton<ICache>(provider => new RedisCache("myPrettyLocalhost:6379",new TimeSpan(1)));

如果有特定原因为什么将键和值类型添加到类中,您可以编辑问题以显示原因吗?

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...