Last active
October 14, 2016 18:19
-
-
Save dataneek/7b9671d2cbaa0b83ec05f40190d473aa to your computer and use it in GitHub Desktop.
Cache Prototype
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 TripsByDateQuery : IQuery<IEnumerable<Trip>> | |
{ | |
public DateTime? Lowerbound { get;set; } | |
public DateTime? UpperBound { get; set; } | |
} | |
public class TripsByDateQueryHandler : IQueryHandler<TripsByDateQuery, IEnumerable<Trip>>, ICachable | |
{ | |
public IEnumerable<Trip> Handle(TripsByDateQuery query) | |
{ | |
//# Do stuff here | |
} | |
} | |
public class RuntimeCachingCachableDecorator<T, U> : IQueryHandler<T, U> where T: IQuery<T> | |
{ | |
private readonly IQueryHandler<T, U> innerHandler | |
public RuntimeCachingCachableDecorator (ICachable cachable) | |
{ | |
this.cachable = cachable; | |
} | |
public U Handle(T query) | |
{ | |
//# check to see if this query is cached. | |
//# if it is, return. | |
//# if not, execute the handler, and cache the result. | |
var cacheKey = GenerateCacheKey(query); | |
if (Cache.ContainsKey(cacheKey)) | |
return Cache.GetFromCache(cacheKey) as U; | |
else | |
{ | |
var result = innerHandler.Handle(query); | |
lock(crap) | |
{ | |
//# Maybe lock again, but who cares. | |
Cache.AddToCache(cacheKey, result); | |
return result; | |
} | |
} | |
} | |
} |
Then, let StructureMap or other IoC containers wire it up at runtime.
Say, if a IQueryHandler implements ICachable, then wrap it with the RuntimeCachingCachableDecorator
Use something like this to configure the cache entry.
public class TripsBySomeOtherDateQuery : IQuery<IEnumerable<Trip>>, ICachableConfigurationProvider
{
public DateTime? OtherDate { get;set; }
public ICachableConfiguration GetCachableConfiguration()
{
return new CachableConfiguration(
cacheKey: "SomeCustomCacheKey",
expiration: = TimeSpan.Hours.Add(1)
)
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be nice if to enable caching, all we need to do was add the ICachable interface.