DEV Community

Luke Lowrey
Luke Lowrey

Posted on • Originally published at lukencode.com on

Caching in ASP.NET Core with LazyCache

Caching is a great way to get improve the performance of your application - either enabling high load scenarios or papering over some bad code to make life bearable. I have always favoured a simple “GetOrCreate” style caching API so when I found the open source LazyCache by Alistair Crabtree I was keen to check it out.

LazyCache describes itself as “An easy to use thread safe generics based in memory caching service with a simple developer friendly API for C#” which I would pretty much have to agree with.

The ASP.NET Core version is currently in beta (though seems to be pretty solid) and can be installed via nuget:

Install-Package LazyCache.AspNetCore -Version 2.0.0-beta03
Enter fullscreen mode Exit fullscreen mode

Once installed it can be easily made available when configuring services in startup:

services.AddLazyCache();
Enter fullscreen mode Exit fullscreen mode

This will inject IAppCache throughout your application.

Here is a simplified example of using LazyCache from the homepage my Australian tech job board - Austechjobs:

IAppCache is the Lazy Cache service being injected into my class. It provides a GetOrAddAsync method that accepts:

  • A cache key which in my example is the string “HomeModel”.
  • A factory to retrieve the data to be cached in the form of a function Func<ICacheEntry, Task> addItemFactory. The code in my example returns a model after making a database call (the bit I wanted to cache).
  • Options for cache length. I am using a simple sliding timespan of 12 hours.

I find the simplicity of this caching setup very pleasing. It’s implementation uses Lazy<T> to ensure the factory method is only executed once. Under the hood by default LazyCache will use IMemoryCache in Microsoft.Extensions.Caching.Memory. This is implementation will only cache data on the machine it is running on. If I was running a more intensive service I would want to extend LazyCache and implement something like redis for distributed caching. The good news is because I am using IAppCache throughout my application I can change the underlying caching provider with relative ease.

Top comments (1)

Collapse
 
nikolicbojan profile image
Bojan Nikolić

Hi,

I made for internal use a simple Memory+Distributed caching service. As you mentioned, it would be nice to have option for Distributed cache also.
Code is so dead-simple, I didn't yet even bother to put it in NuGet.

Since I do not need all LazyCache offers, I have one dependency less.
Check it out if you have time dev.to/nikolicbojan/memory-distrib...