Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created November 3, 2016 01:08
Show Gist options
  • Save dcomartin/66ae82d3c0559e6a111d1d12405d6a0e to your computer and use it in GitHub Desktop.
Save dcomartin/66ae82d3c0559e6a111d1d12405d6a0e to your computer and use it in GitHub Desktop.
public class HomeHandler : IAsyncRequestHandler<Home, List<Album>>
{
private readonly MusicStoreContext _dbContext;
private readonly IMemoryCache _cache;
private readonly IOptions<AppSettings> _options;
public HomeHandler(MusicStoreContext dbContext, IMemoryCache cache, IOptions<AppSettings> options)
{
_dbContext = dbContext;
_cache = cache;
_options = options;
}
public async Task<List<Album>> Handle(Home message)
{
// Get most popular albums
var cacheKey = "topselling";
List<Album> albums;
if (!_cache.TryGetValue(cacheKey, out albums))
{
albums = await _dbContext.Albums
.OrderByDescending(a => a.OrderDetails.Count)
.Take(6)
.ToListAsync();
if (albums != null && albums.Count > 0)
{
if (_options.Value.CacheDbResults)
{
// Refresh it every 10 minutes.
// Let this be the last item to be removed by cache if cache GC kicks in.
_cache.Set(
cacheKey,
albums,
new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
.SetPriority(CacheItemPriority.High));
}
}
}
return albums;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment