StashCache is an in-memory caching library for your .NET application. Under the hood, it uses the MemoryCache from Microsoft.Extensions.Caching.Memory.
Developers tend to procrastinate caching because oftentimes it is divorced from retrieving of data. StashCache is designed such that retrieving and caching of data is inside the same method block.
StashCache is available on nuget.
See example in Sample.AspNetCore project in this repo.
- Register the extension method for the service in
Startup.ConfigureServices.
publicvoidConfigureServices(IServiceCollectionservices){// Import namespace:// using StashCache;services.AddStashCache();}Choose cache key generator; or implement one as the need arises.
TypeCacheKeyGeneratorcan be selected in order to generate cache key which is structured into:type/class+method+additional segments.
// From Sample.AspNetCore WeatherForecastService classprivatestaticreadonlyICacheKeyGenerator<TypeCacheKeyGenerator>CacheKeyGenerator=CacheKeyGeneratorFactory.GetCacheKeyGenerator<TypeCacheKeyGenerator>();privatestaticreadonlyTimeSpanDefaultCacheExpiry=TimeSpan.FromHours(1);- Inject
ILocalCacheto a class which retrieves data
privatereadonlyILocalCache_localCache;publicWeatherForecastService(ILocalCache localCache){_localCache=localCache;}- Lastly, implement caching in the same method block as the data retrieval.
publicasyncTask<IEnumerable<WeatherForecast>>GetAll(CancellationTokencancellationToken){varcacheKey=CacheKeyGenerator.GenerateCacheKey<WeatherForecastService>();varresult=await_localCache.GetOrAddAsync(cacheKey,async()=>{varsummaries=awaitGetSummariesAsyc();// This can be your database callreturnsummaries;},DefaultCacheExpiry,cancellationToken).ConfigureAwait(false);returnresult;}Benchmark using BenchmarkDotNet
| Method | # of Cached Items | Total # of retrievals | Mean (μs) | StdDev (μs) | Allocated (KB) |
|---|---|---|---|---|---|
| GetOrAddAsync | 100 | 1 | 61.05 | 2.416 | 57 |
| GetOrAddAsync | 100 | 10 | 609.78 | 5.298 | 568 |
| GetOrAddAsync | 100 | 100 | 5,829.17 | 121.375 | 5,675 |
| GetOrAddAsync | 100 | 500 | 29,906.00 | 201.832 | 28,376 |
| GetOrAddAsync | 500 | 500 | 156,081.09 | 2,215.348 | 142,444 |
| GetOrAddAsync | 1000 | 500 | 306,005.04 | 2,911.767 | 285,028 |