问题描述
这是我的代码:
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)));
如果有特定原因为什么将键和值类型添加到类中,您可以编辑问题以显示原因吗?