Search this site

6 October 2010 ·

Object Caching - .NET 4

As a developer, we need to use all the tools at our disposal to develop faster and more robust applications. One of the ways we can achieve this is by using caching. Caching is the process of storing frequently used data on the server to fulfil subsequent requests. Now there are a few different types of caching available to the .NET developer, but in this article I am going to discuss data caching using the object cache. The cache object enables you to store everything from simple name / value pairs to more complex objects such as datasets and entire pages.

Previously, the cache object used to fall under the System.Web.Caching.Cache namespace. Due to it's power and awesomeness, many developers would copy this namespace into their projects and use it in other applications such as Windows Forms and WPF apps. With the release of .NET 4, the namespace has been refactored and totally rebuilt into the new namespace of System.Runtime.Caching. The old namespace is still available, but any new enhancements will be added to the System.Runtime.Caching namespace.

In this example, I am going to take a look at Object Caching. For more types of caching available to you in the .net framework - check out this link. Now, let's look at a code example and run through how easy it is to add some caching to your application. I'm going to use an example of some of the caching I use when building on this site.

To start, you add a reference to the System.Runtime.Caching object in your project.

Add Reference

The CacheLayer helper uses the default MemoryCache instance. The .NET caching runtime also allows multiple MemoryCache instances in one application.

public class CacheLayer
{
    private static readonly ObjectCache Cache = MemoryCache.Default;

    public static T Get<T>(string key) where T : class
    {
        try
        {
            return (T)Cache[key];
        }
        catch
        {
            return null;
        }
    }

    public static void Add<T>(T objectToCache, string key) where T : class
    {
        Cache.Add(key, objectToCache, DateTime.Now.AddDays(30));
    }
}

Get<T> retrieves a cached value, and Add<T> stores it under a key for 30 days. If similar objects need distinct entries, build a dynamic key. Call the retrieval method with the type you expect:

List<string> customerNames = CacheLayer.Get<List<string>>(cacheKey);

Here is the complete example. It checks the cache first, loads the names from the database on a miss, and then caches them for the next call:

public List<string> CachingExample()
{
    const string cacheKey = "CustomerNames";

    // Check the cache
    List<string> customerNames = CacheLayer.Get<List<string>>(cacheKey);

    if (customerNames == null)
    {
        // Go and retrieve the data from the DB
        customerNames = GetCustomerNames();

        // Then add it to the cache so we can retrieve it next time
        CacheLayer.Add(customerNames, cacheKey);
    }

    return customerNames;
}

The first call retrieves the data from the database and caches it. Later calls can use the in-memory value instead of querying the database again.

NOTE: If you make changes on your application, you might not see them immediately because they might be in cache. You might need to remove the object in order to see your changes - you can always add them back in!

In order to wrap all this up, I have created a little class that you can easily call and use for your caching needs. If you would like to download just the class file - click here

Else if you prefer to download the full class library project with working unit tests

Download

READ MORE