Click here to Skip to main content
Licence CPOL
First Posted 3 Sep 2008
Views 22,650
Bookmarked 22 times

Generic Lazy Load Cache Class

By | 5 Sep 2008 | Article
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Laughing.John

Software Developer (Senior)

United Kingdom United Kingdom

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralA simpler technique PinmemberPIEBALDconsult20:46 4 Sep '08  
GeneralRe: A simpler technique PinmemberLaughing.John22:49 4 Sep '08  
GeneralRe: A simpler technique PinmemberPIEBALDconsult4:38 5 Sep '08  
GeneralRe: A simpler technique PinmemberLaughing.John8:56 5 Sep '08  
GeneralRe: A simpler technique PinmemberPIEBALDconsult10:47 5 Sep '08  
GeneralRe: A simpler technique PinmemberLaughing.John12:58 5 Sep '08  
GeneralRe: A simpler technique PinmemberPIEBALDconsult13:39 5 Sep '08  
GeneralRe: A simpler technique Pinmemberjonnii9:04 5 Sep '08  
GeneralRe: A simpler technique PinmemberPIEBALDconsult10:50 5 Sep '08  
AnswerRe: A simpler technique Pinmemberflops4211:50 6 Sep '08  
GeneralSingletons Pinmemberjonnii5:33 4 Sep '08  
GeneralRe: Singletons PinmemberLaughing.John6:54 4 Sep '08  
GeneralRe: Singletons PinmemberLaughing.John7:04 4 Sep '08  
GeneralRe: Singletons Pinmemberjonnii8:01 4 Sep '08  
GeneralRe: Singletons PinmemberPIEBALDconsult11:25 4 Sep '08  
GeneralRe: Singletons PinmemberLaughing.John14:37 4 Sep '08  
GeneralRe: Singletons Pinmembersupercat912:37 4 Sep '08  
GeneralRe: Singletons PinmemberLaughing.John14:29 4 Sep '08  
GeneralRe: Singletons Pinmemberjonnii9:18 5 Sep '08  
GeneralRe: Singletons PinmemberPIEBALDconsult8:43 4 Sep '08  
GeneralRe: Singletons PinmemberLaughing.John14:43 4 Sep '08  
GeneralThoughts PinmemberPIEBALDconsult15:55 3 Sep '08  
GeneralRe: Thoughts [modified] PinmemberLaughing.John22:39 3 Sep '08  
GeneralRe: Thoughts PinmemberPIEBALDconsult3:27 4 Sep '08  
GeneralRe: Thoughts PinmemberLaughing.John3:39 4 Sep '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 5 Sep 2008
Article Copyright 2008 by Laughing.John
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid