Skip to content

Instantly share code, notes, and snippets.

@dataneek
Last active August 29, 2015 14:28
Show Gist options
  • Save dataneek/a46120e5de8fa4837505 to your computer and use it in GitHub Desktop.
Save dataneek/a46120e5de8fa4837505 to your computer and use it in GitHub Desktop.
Generic interface for identifying messages that participate in caching operations.
public class CachableRequestHandler<TRequest, TResponse>
: IAsyncRequestHandler<TRequest, TResponse>
where TRequest : IAsyncRequest<TResponse>, ICacheable<TRequest>
where TResponse : class
{
private readonly IAsyncRequestHandler<TRequest, TResponse> innerHandler;
private readonly ObjectCache objectCache;
private readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
public CachableRequestHandler(IAsyncRequestHandler<TRequest, TResponse> innerHandler, ObjectCache objectCache)
{
this.innerHandler = innerHandler;
this.objectCache = objectCache;
}
Task<TResponse> IAsyncRequestHandler<TRequest, TResponse>.Handle(TRequest message)
{
var cacheKey = message.GetCacheKey();
cacheLock.EnterReadLock();
TResponse cachedResult = this.objectCache.Get(cacheKey, null) as TResponse;
cacheLock.ExitReadLock();
if (cachedResult == null)
{
cacheLock.EnterWriteLock();
try
{
cachedResult = this.innerHandler.Handle(message).Result;
var policy = message.GetPolicy();
this.objectCache.Set(cacheKey, cachedResult, policy);
}
finally
{
cacheLock.ExitWriteLock();
}
}
return Task.FromResult(cachedResult);
}
}
public interface ICacheable<T>
{
CacheItemPolicy GetPolicy();
string GetCacheKey();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment