Last active
May 20, 2018 23:45
-
-
Save lukencode/f974c562b2e48c9cbad63aa768ddb4a7 to your computer and use it in GitHub Desktop.
LazyCache Example
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 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