Skip to content

Life without LazyCache (v0.7.x)

Alastair Crabtree edited this page Feb 25, 2019 · 1 revision

Imagine you were caching all the products in your e-commerce website to make the shopping pages load faster

If you have ever added caching to a c# application you probably wrote something like this. Later we show you a better way.

    // Get the cache
    ObjectCache cache = MemoryCache.Default;

    //check if we have fetched the products before
    var products = cache["all-products"] as ICollection<Product>;

    if (products == null) // More than one thread can get inside here before products are cached!
    {
        // Products not cached so fetch them
        products = dbContext.Products.ToList();

        // Add them to the cache for later
        cache["all-products"] = products;
    }

    // Now actually do something with the products...

This pattern of check cache > do something > add to cache quickly gets scattered across your application and is tedious and repetitive.

Lazy cache offers a tidy api to make this a simple one liner. In addition we handle the issue of multiple threads hitting your code at the same time and finding nothing in the cache for you, so you don't need to think about locking.