Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Created March 31, 2019 02:58
Show Gist options
  • Save changhuixu/1304f98f24c76f520ca5b769f8c1598d to your computer and use it in GitHub Desktop.
Save changhuixu/1304f98f24c76f520ca5b769f8c1598d to your computer and use it in GitHub Desktop.
public class LotNamesCache : ILotNamesCache
{
public const string CacheKey = nameof(LotNamesCache);
private readonly ImmutableCacheDbContext _dbContext;
private readonly IMemoryCache _cache;
public LotNamesCache(ImmutableCacheDbContext dbContext, IMemoryCache cache)
{
_dbContext = dbContext;
_cache = cache;
}
public async Task<ImmutableDictionary<string, string>> LotNamesDictionary()
{
if (!_cache.TryGetValue(CacheKey, out ImmutableDictionary<string, string> result))
{
var lotNames = await _dbContext.ParkingLots.AsNoTracking().ToListAsync();
result = lotNames.ToImmutableDictionary(x => x.LotCode, x => x.LotName);
var options = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromDays(1));
_cache.Set(CacheKey, result, options);
}
return result;
}
public void RemoveCachedDictionary()
{
_cache.Remove(CacheKey);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment