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.
public static class Caching
/// A generic method for getting and setting objects to the memory cache.
/// <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);
int resultOfExpensiveQuery = GetObjectFromCache<int>("resultOfExpensiveQuery", 10, CallSlowQueryFromDatabase);
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.
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.
To see an example of this code being used, have a look at my site navigation model post.
This post will show you how you can include scripts from inside an MVC partial view rather than havi…Read Post
This post will show you how to fix the error "Authentication failed because the remote party has clo…Read Post
This post help you solve the error System.IO.FileNotFoundException Could not load file or assembly S…Read Post
This post will show you how to solve the error "Could not load file or assembly 'Microsoft.CodeDom.P…Read Post