Skip to content

Instantly share code, notes, and snippets.

@lukencode
Last active May 20, 2018 23:45
Show Gist options
  • Save lukencode/f974c562b2e48c9cbad63aa768ddb4a7 to your computer and use it in GitHub Desktop.
Save lukencode/f974c562b2e48c9cbad63aa768ddb4a7 to your computer and use it in GitHub Desktop.
LazyCache Example
public class HomePageService
{
public static string HomeModelCacheKey = "HomeModel";
private static TimeSpan cacheExpiry = new TimeSpan(12, 0, 0); //12 hours
private readonly PositionsGroupedByTagQuery positionsGroupedByTagQuery;
private readonly IAppCache cache;
public HomePageService(PositionsGroupedByTagQuery positionsGroupedByTagQuery, IAppCache cache)
{
this.positionsGroupedByTagQuery = positionsGroupedByTagQuery;
this.cache = cache;
}
public async Task<HomeModel> GetHomeModel(string tag, bool bustCache = false)
{
if (bustCache) ClearHomePageCache();
var model = await cache.GetOrAddAsync(HomeModelCacheKey, async () =>
{
return new HomeModel()
{
GroupedLatestListings = await positionsGroupedByTagQuery.Execute(tag)
};
}, cacheExpiry);
return model;
}
public void ClearHomePageCache() => cache.Remove(HomeModelCacheKey);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment