Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Generic Lazy Load Cache Class

0.00/5 (No votes)
5 Sep 2008 1  
Presents a base class for creating a singleton lazy load cache.

Introduction

This generic class can be inherited and used as a simple memory cache for lazy loading objects.

Background

In my applications, I noticed I was often implementing a lazy load cache. I use it for static or near-static data that I am loading from a database and which I don't want to have in an object graph multiple times.

The requirements for the class are:

  • Loading of objects only once. After the initial load, requests for the object would return the copy already in memory (i.e. Lazy Load).
  • A Singleton pattern for the cache so that there is only one instance ever.
  • Retrieval of objects via a key object (dictionary).
  • Derived classes are responsible for the initial load of an object.

Having done this a few times, it seemed to me that I should be able to use Generics to create a reusable base class for my cache. I wanted to use the Template pattern so that each derived class implements its own loading mechanism, and combine this with the Singleton pattern.

Using the Code

To use the code, you simply inherit from the base class. The derived class needs a private/protected constructor to make sure it cannot be instantiated directly, and needs to override the GetItem member to actually obtain the object from somewhere when it is not in the cache.

There are three types that must be supplied:

  1. T: The type of the class which is inheriting the LazyLoadCacheBase class.
  2. TKey: The type of the key.
  3. TValue: The type of the objects stored in the cache.

Here's the class:

/// <summary>
/// This base class can be inherited to implement a lazy load cache
/// </summary>
/// <typeparam name="T">Pass in the type of the derived class (the type of the class that 
/// inherits this base class)</typeparam>
/// <typeparam name="TKey">Type of the dictionary key objects</typeparam>
/// <typeparam name="TValue">Type of the dictionary value objects</typeparam>
internal abstract class LazyLoadCacheBase<T, TKey,
    TValue> where T: LazyLoadCacheBase<T, TKey, TValue>
{
    private Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();

    abstract protected TValue GetItem(TKey key);

    protected LazyLoadCacheBase()
    {
    }

    public static T Instance
    {
        get
        {
            return Creator.Singleton;
        }
    }

    public Dictionary<TKey, TValue> Dictionary
    {
        get { return _dictionary; }
        set {_dictionary = value;}
    }

    public TValue GetValue(TKey key)
    {
        if (!_dictionary.ContainsKey(key))
        {
            TValue item = GetItem(key);
            _dictionary.Add(key, item);
        }
        return _dictionary[key];
    }

    private sealed class Creator
    {
        private static readonly T _instance = (T)typeof(T).InvokeMember(typeof(T).Name,
            BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Instance,
            null, null, null);

        internal static T Singleton
        {
            get { return _instance; }
        }
    }

}

An example of using the class:

internal class MyObjectCache: LazyLoadCacheBase<MyObjectCache, int, IMyObject %gt;
{
    // Prevent direct instantiation
    private MyObjectCache()
    {
    }

    protected override IMyObject GetItem(int key)
    {
        
        IMyObject item = GetMyObjectFromDB(key);
        return item;
    }
}

Points of Interest

  • In order to maintain the derived classes as Singletons, they need to have a private or protected constructor. This necessitated the use of Reflection to instantiate the Singleton.
  • In my implementation, I expose the internal dictionary in case I want to load all of the items at once and to give flexibility. The required functionality should really be encapsulated (for example, a LoadAll method).
  • I have deliberately kept the class very simple. If you have additional requirements, it should be easy to add them yourself. For example, items loaded into the cache remain until the application is closed. Obviously, you could include a mechanism for removing items from the cache based on an expiry time or some other criteria.

History

  • Initial submission.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here