【发布时间】:2012-04-21 14:09:39
【问题描述】:
我想为缓存创建 Aspect。我需要知道如何从方法调用中创建缓存键并将其插入缓存并返回值。是否有任何解决方案可用于这部分。我不需要完整的缓存解决方案
谢谢
【问题讨论】:
标签: c# .net caching distributed-caching
我想为缓存创建 Aspect。我需要知道如何从方法调用中创建缓存键并将其插入缓存并返回值。是否有任何解决方案可用于这部分。我不需要完整的缓存解决方案
谢谢
【问题讨论】:
标签: c# .net caching distributed-caching
我以前使用过RealProxy 来实现这种类型的功能。我在博客文章中展示了一些示例; Intercepting method invocations using RealProxy。
缓存代理的快速示例,使用方法的哈希码(以确保具有相同参数的两个不同方法分别缓存)和参数。请注意,没有处理输出参数,只有返回值。 (如果您想更改它,您需要更改 _cache 以保存包含返回值和输出参数的对象。)此外,此实现没有表单 av 线程安全性。
public class CachingProxy<T> : ProxyBase<T> where T : class {
private readonly IDictionary<Int32, Object> _cache = new Dictionary<Int32, Object>();
public CachingProxy(T instance)
: base(instance) {
}
protected override IMethodReturnMessage InvokeMethodCall(IMethodCallMessage msg) {
var cacheKey = GetMethodCallHashCode(msg);
Object result;
if (_cache.TryGetValue(cacheKey, out result))
return new ReturnMessage(result, msg.Args, msg.ArgCount, msg.LogicalCallContext, msg);
var returnMessage = base.InvokeMethodCall(msg);
if (returnMessage.Exception == null)
_cache[cacheKey] = returnMessage.ReturnValue;
return returnMessage;
}
protected virtual Int32 GetMethodCallHashCode(IMethodCallMessage msg) {
var hash = msg.MethodBase.GetHashCode();
foreach(var arg in msg.InArgs) {
var argHash = (arg != null) ? arg.GetHashCode() : 0;
hash = ((hash << 5) + hash) ^ argHash;
}
return hash;
}
}
【讨论】: