Recently came across this small but highly effective caching library called LazyCache. While I have been familiar with the in-memory caching functionalities of .Net such as ObjectCache and MemoryCache, LazyCache provides a neat threadsafe wrapper around the conventional options. It also make sure you don’t need to implement the Cache Aside pattern yourself as the library takes care of it themselves.
Let’s write an example code to demonstrate the usage.
_cache = new CachingService(new MemoryCacheProvider(new MemoryCache(new MemoryCacheOptions()))); _cache.GetOrAdd("Test", () => GetFromWebService());
As you can see, the usage is pretty simple and straightforward. The highly effective design of GetOrAdd method allows you to fetch the cached data from memory, or if not, it is unavailable, evaluate the Func delegate to fetch the required data from the original source.
The ability to inject the caching service means, you could also take advantage of other services like the Redis ObjectCache.