Articles in categories

Articles

Extended caching (with CacheManager)

In my earlier article (Simple Caching) I explained the simple use of the dotnet framework ObjectCache which I used for an application. It was the first time I used the ObjectCache object and it works fine.

Recently I changed over to my own CacheManager class to manage caching. Got this from a colleque on my work and it works perfectly.
It's a static class which holds a static variable Cache. That Cache class can contain any variables you need. Just simply add them. You can fill and read the variables and even clear the entire cache.

Usage in the code easy:

 var users = CacheManager.Cache.Users;

Clear the cache:

CacheManager.ClearCache();

 The actual class:

namespace WpfRibbonTestApplication.Model
{
  /// <summary>
  /// Static CacheManager class
  /// </summary>
  public static class CacheManager
  {
    private static Cache _cache;

    public static Cache Cache
    {
      get { return _cache ?? (_cache = new Cache()); }
    }

    /// <summary>
    /// Clears the cache object
    /// </summary>
    public static void ClearCache()
    {
      _cache = null;
    }
  }

  /// <summary>
  /// Public Cache class
  /// </summary>
  public class Cache
  {
    private static List<string> _users;

    public Cache()
    {
    }

    /// <summary>
    /// Loads the users from the database via the Person class
    /// If the var _users is already filled it just returns it.
    /// If the var _users is null it will be filled from a method on the Person class
    /// </summary>
    public List<string> Users
    {
      get { return _users ?? (_users = Person.GetUsersFromDatabase()); }
    }
  }
}

I made a habbit out of it to include this class standard in my projects. That way I can always use the CacheManager if I would need it...