5,699,997 members and growing! (11,650 online)
Email Password   helpLost your password?
Languages » C# » Generics     Intermediate License: The Code Project Open License (CPOL)

Generic Lazy Load Cache Class

By Laughing.John

Presents a base class for creating a singleton lazy load cache.
C# (C# 2.0, C# 3.0, C#), Windows, .NET (.NET, .NET 2.0, .NET 3.5, .NET 3.0), Dev

Posted: 3 Sep 2008
Updated: 5 Sep 2008
Views: 4,689
Bookmarked: 16 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
4 votes for this Article.
Popularity: 1.96 Rating: 3.25 out of 5
1 vote, 25.0%
1
1 vote, 25.0%
2
0 votes, 0.0%
3
0 votes, 0.0%
4
2 votes, 50.0%
5

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



Occupation: Software Developer (Senior)
Location: United Kingdom United Kingdom

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
GeneralA simpler techniquememberPIEBALDconsult21:46 4 Sep '08  
GeneralRe: A simpler techniquememberLaughing.John23:49 4 Sep '08  
GeneralRe: A simpler techniquememberPIEBALDconsult5:38 5 Sep '08  
GeneralRe: A simpler techniquememberLaughing.John9:56 5 Sep '08  
GeneralRe: A simpler techniquememberPIEBALDconsult11:47 5 Sep '08  
GeneralRe: A simpler techniquememberLaughing.John13:58 5 Sep '08  
GeneralRe: A simpler techniquememberPIEBALDconsult14:39 5 Sep '08  
GeneralRe: A simpler techniquememberjonnii10:04 5 Sep '08  
GeneralRe: A simpler techniquememberPIEBALDconsult11:50 5 Sep '08  
AnswerRe: A simpler techniquememberflops4212:50 6 Sep '08  
GeneralSingletonsmemberjonnii6:33 4 Sep '08  
GeneralRe: SingletonsmemberLaughing.John7:54 4 Sep '08  
GeneralRe: SingletonsmemberLaughing.John8:04 4 Sep '08  
GeneralRe: Singletonsmemberjonnii9:01 4 Sep '08  
GeneralRe: SingletonsmemberPIEBALDconsult12:25 4 Sep '08  
GeneralRe: SingletonsmemberLaughing.John15:37 4 Sep '08  
GeneralRe: Singletonsmembersupercat913:37 4 Sep '08  
GeneralRe: SingletonsmemberLaughing.John15:29 4 Sep '08  
GeneralRe: Singletonsmemberjonnii10:18 5 Sep '08  
GeneralRe: SingletonsmemberPIEBALDconsult9:43 4 Sep '08  
GeneralRe: SingletonsmemberLaughing.John15:43 4 Sep '08  
GeneralThoughtsmemberPIEBALDconsult16:55 3 Sep '08  
GeneralRe: Thoughts [modified]memberLaughing.John23:39 3 Sep '08  
GeneralRe: ThoughtsmemberPIEBALDconsult4:27 4 Sep '08  
GeneralRe: ThoughtsmemberLaughing.John4:39 4 Sep '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Sep 2008
Editor: Sean Ewington
Copyright 2008 by Laughing.John
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project