我正在使用ASP.NET核心和Redis。我试图在缓存中存储不同类型的不同对象,并且希望避免显式转换。
这是我的红宝石缓存的包装器
public class RedisCacheStorage : Contracts.ICacheStorage
{
private CachingFramework.Redis.Context _context = null;
public RedisCacheStorage(string configuration)
{
_context = new CachingFramework.Redis.Context(configuration, new CachingFramework.Redis.Serializers.JsonSerializer());
}
public void SetItem<T>(string key, T value)
{
_context.Cache.SetObject<T>(key, value);
}
public T GetItem<T>(string key)
{
return _context.Cache.GetObject<T>(key);
}
public T GetItem<T>(string key, Func<T> loadCacheFunc)
{
return _context.Cache.FetchObject<T>(key, loadCacheFunc);
}然后我将ICacheStorage注入到CacheManager (实现ICacheManager)中。我试图隔离依赖项并保持CacheStorage的简单性,所以当我需要更改缓存类型时,我只需实现ICacheStorage。在CacheManager中,我们将在传递特殊密钥时注入获取某些数据的所有服务。
CacheManager
public class CacheManager : Contracts.ICacheManager
{
private Contracts.ICacheStorage _cacheStorage;
private SecurityCore.ServiceContracts.IParametersService _paramService;
public CacheManager(Contracts.ICacheStorage cacheStorage, SecurityCore.ServiceContracts.IParametersService paramService)
{
_cacheStorage = cacheStorage;
_paramService = paramService;
}
public Object GetItem(string key)
{
if (key == Constants.CacheKeys.SecuritySystemParams)
return _cacheStorage.GetItem<Dictionary<string, string>>(key, _paramService.GetSystemParameters);
//if (key == Constants.CacheKeys.EffectivePermissions)
// return List of Effective Permissions
return _cacheStorage.GetItem<Object>(key);
}_cacheStorage.GetItem<Dictionary<string, string>>(key, _paramService.GetSystemParameters);
传递一个函数,该函数使用Redis的Fetch方法,如果缓存为空,则调用服务,然后将数据存储在缓存中并返回。
我的问题是我需要避免转换,因为我可能返回不同的对象,如何继续使用Generics,所以我传递返回对象的类型。
正如您在下面看到的编译错误,由于无法将类型对象转换为Dictionay,这需要显式转换才能解决。
有没有更好、更优雅的方法来实现整个想法?

发布于 2016-11-07 15:22:16
读取错误消息。
您需要显式指定类型参数。
通过使用类型安全的密钥,您可以做得更好:
class CacheKey<T> {
public string Name { get; }
public string ToString() => Name;
public CacheKey(string name) { Name = name; }
}
public T GetItem<T>(CacheKey<T> key) { ... }
public CacheKey<Dictionary<string, string>> SecuritySystemParams { get; } = new CacheKey<Dictionary<string, string>>("SecuritySystemParams");这将使GetItem()从键中推断出T,并防止您传递错误的类型。
https://stackoverflow.com/questions/40468614
复制相似问题