Skip to content

Repository files navigation

StashCache

StashCache is an in-memory caching library for your .NET application. Under the hood, it uses the MemoryCache from Microsoft.Extensions.Caching.Memory.

Why StashCache?

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.

Download

StashCache is available on nuget.

Getting Started

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.

    TypeCacheKeyGenerator can 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 ILocalCache to 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 ItemsTotal # of retrievalsMean (μs)StdDev (μs)Allocated (KB)
GetOrAddAsync100161.052.41657
GetOrAddAsync10010609.785.298568
GetOrAddAsync1001005,829.17121.3755,675
GetOrAddAsync10050029,906.00201.83228,376
GetOrAddAsync500500156,081.092,215.348142,444
GetOrAddAsync1000500306,005.042,911.767285,028

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages