Why is caching important?

Caching is important because it can speed up your website or application. Why spend time and resources by needless calls to the database each time a user visits a page or uses an app?

Here is an example for you to read and use yourself.

using System;
using System.Runtime.Caching;
namespace CodeShare.Web.App_Code.Helpers
{
    public static class Caching
    {
        /// <summary>
        /// A generic method for getting and setting objects to the memory cache.
        /// </summary>
        /// <typeparam name="T">The type of the object to be returned.</typeparam>
        /// <param name="cacheItemName">The name to be used when storing this object in the cache.</param>
        /// <param name="cacheTimeInMinutes">How long to cache this object for.</param>
        /// <param name="objectSettingFunction">A parameterless function to call if the object isn't in the cache and you need to set it.</param>
        /// <returns>An object of the type you asked for</returns>
        public static T GetObjectFromCache<T>(string cacheItemName, int cacheTimeInMinutes, Func<T> objectSettingFunction)
        {
            ObjectCache cache = MemoryCache.Default;
            var cachedObject = (T)cache[cacheItemName];
            if (cachedObject == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(cacheTimeInMinutes);
                cachedObject = objectSettingFunction();
                cache.Set(cacheItemName, cachedObject, policy);
            }
            return cachedObject;
        }
    }
}

Usage

int resultOfExpensiveQuery = GetObjectFromCache<int>("resultOfExpensiveQuery", 10, CallSlowQueryFromDatabase);

Parameters

The above code accepts 3 parameters. The first one is the name. When storing an object in the cache, it uses a name, so you can call it later or replace it later.

The next parameter is the cache time in minutes. This tells the application how long to store the object in the cache for.

The last parameter is the clever part. This is a delegate function. This gets called if the object isn't in the cache so the object can be set and stored in the cache. You can change this delegate function to accept parameters into it.

Generic method

The last thing to note is the use of T in the angled brackets and inside the method. This makes it a generic method. When you call the method you can tell it what Type T is.
It will return your cached object back in the form of whatever you specified T as.

A good use for this code would be the site navigation. There is no point recreating it for every page view or every user.

Real world example

To see an example of this code being used, have a look at my site navigation model post.

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Proudly sponsored by

Moriyama

  • Moriyama build, support and deploy Umbraco, Azure and ASP.NET websites and applications.
AppVeyor

  • CI/CD service for Windows, Linux and macOS
  • Build, test, deploy your apps faster, on any platform.
elmah.io

  • elmah.io is the easy error logging and uptime monitoring service for .NET.
  • Take back control of your errors with support for all .NET web and logging frameworks.
uSync Complete

  • uSync.Complete gives you all the uSync packages, allowing you to completely control how your Umbraco settings, content and media is stored, transferred and managed across all your Umbraco Installations.
uSkinned

  • More than a theme for Umbraco CMS, take full control of your content and design with a feature-rich, award-nominated & content editor focused website platform.
UmbHost

  • Affordable, Geo-Redundant, Umbraco hosting which gives back to the community by sponsoring an Umbraco Open Source Developer with each hosting package sold.