我正在尝试缓存从存储库返回的实体。我正在拦截对存储库方法的调用,以便我可以检查请求的数据是否存在于缓存中。但是,由于我正在拦截方法调用,所以我无法获取真正的实体类型,您可能会猜到我得到了一个 EF 代理类型。因此,当我将其放入缓存时,我并没有放入真正的实体,而是放入了它的子类。
我记得 Nhibernate 有一些实用程序可以立即初始化代理。我们可以在 EF 6 中做到这一点吗?我怎样才能在这里获得基础实体?
这是我的一些代码来阐明我的需求。顺便说一句,我正在使用 Castle Interceptors。
public class CacheInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (IsReturnTypeCacheable(invocation.Method.ReturnType))
{
string cacheKey = this.CreateCacheKey(invocation.Method.Name, invocation.Arguments);
object returnValue = this.GetFromCache<object>(cacheKey);
if (returnValue != null)
{
invocation.ReturnValue = returnValue;
return;
}
else
{
invocation.Proceed();
object actualValue = invocation.ReturnValue;
Type proxyType = invocation.ReturnValue.GetType();
Type pocoType = proxyType.BaseType;
var dataInstance = Activator.CreateInstance(pocoType);
dataInstance = invocation.ReturnValue;
this.PutToCache(cacheKey, dataInstance);// This puts the proxy type to cache, not underlying POCO...
}
}
else
{
invocation.Proceed();
}
}
private bool IsReturnTypeCacheable(Type type)
{
//some custom checks
}
public T GetFromCache<T>(string cacheKey) where T : class
{
IRedisNativeClient redisClient = new RedisNativeClient("myredis");
byte[] obj = redisClient.Get(cacheKey);
if (obj == null) return null;
return Serializer.Deserialize<T>(obj);
}
public void PutToCache(string cacheKey, object value)
{
if (value == null) return;
IRedisNativeClient redisClient = new RedisNativeClient("myredis");
redisClient.Set(cacheKey, Serializer.Serialize(value));
}
public string CreateCacheKey(string method, object[] arguments)
{
//creates cache key
}
}