Skip to content

Instantly share code, notes, and snippets.

@dataneek
Last active October 14, 2016 18:19
Show Gist options
  • Save dataneek/7b9671d2cbaa0b83ec05f40190d473aa to your computer and use it in GitHub Desktop.
Save dataneek/7b9671d2cbaa0b83ec05f40190d473aa to your computer and use it in GitHub Desktop.
Cache Prototype
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;
}
}
}
}
@dataneek
Copy link
Author

It would be nice if to enable caching, all we need to do was add the ICachable interface.

@dataneek
Copy link
Author

Then, let StructureMap or other IoC containers wire it up at runtime.

Say, if a IQueryHandler implements ICachable, then wrap it with the RuntimeCachingCachableDecorator

@dataneek
Copy link
Author

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