I have a repository decorator. This decorator is responsible of the caching of the decorated repository. In most of my functions of this decorator I just return the result for the cache if exist or call the method on the decorated repository and store this result in the cache if not yet in this cache. I do that thead safe.
But I would like to do this routine of getting the cache lock, ... in a single method and call it with a lambda expression.
My method to get the result for the cache or load it:
private X CallCachedAndLocked<X>(string methodCacheKey, xxx methodToCallWithParameter)
{
var cacheKey = GetCacheKey(methodCacheKey);
X obj = (X)Cache.Get(cacheKey);
if (obj == null)
{
lock (getLastDrawResult_lock)
{
if (obj == null)
{
obj = methodToCallWithParameter;
if (obj != null)
{
Cache.Add(cacheKey,
obj,
null,
NextExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
CacheItemPriority.AboveNormal, null);
}
}
}
}
}
Examples of calls:
public T GetDraw(int id)
{
return CallCachedAndLocked<T>(() => _decoratedRepository.GetDraw(id));
}
public IEnumerable<T> GetDraws(DateTime from)
{
return CallCachedAndLocked<T>(() => _decoratedRepository.GetDraws(GetDraws));
}