Lazy Cache

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s