Last active
August 29, 2015 14:28
-
-
Save dataneek/a46120e5de8fa4837505 to your computer and use it in GitHub Desktop.
Generic interface for identifying messages that participate in caching operations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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