Generic wrapper for System.Web.Caching.Cache functions

Posted by David Neale on Stack Overflow See other posts from Stack Overflow or by David Neale
Published on 2010-06-17T12:35:36Z Indexed on 2010/06/17 14:23 UTC
Read the original article Hit count: 522

I've created a generic wrapper for using the Cache object:

public class Cache<T> where T : class
{
    public Cache Cache {get;set;}
    public CachedKeys Key {get;set;}

    public Cache(Cache cache, CachedKeys key){
        Cache = cache;
        Key = key;
    }

    public void AddToCache(T obj){
        Cache.Add(Key.ToString(),
            obj,
            null,
            DateTime.Now.AddMinutes(5),
            System.Web.Caching.Cache.NoSlidingExpiration,
            System.Web.Caching.CacheItemPriority.Normal,
            null);                   
    }

    public bool TryGetFromCache(out T cachedData) {
        cachedData = Cache[Key.ToString()] as T;
        return cachedData != null;
    }

    public void RemoveFromCache() {
        Cache.Remove(Key.ToString()); }
}

The CachedKeys enumeration is just a list of keys that can be used to cache data.

The trouble is, to call it is quite convuluted:

var cache = new Cache<MyObject>(Page.Cache, CachedKeys.MyKey);
MyObject myObject = null;

if(!cache.TryGetFromCache(out myObject)){
    //get data...
    cache.AddToCache(data); //add to cache
    return data;
}

return myObject;

I only store one instance of each of my objects in the cache.

Therefore, is there any way that I can create an extension method that accepts the type of object to Cache and uses (via Reflection) its Name as the cache key?

public static Cache<T> GetCache(this Cache cache, Type cacheType){
        Cache<cacheType> Cache = new Cache<cacheType>(cache, cacheType.Name);
    }

Of course, there's two errors here:

  • Extension methods must be defined in a non-generic static class
  • The type or namespace name 'cacheType' could not be found

This is clearly not the right approach but I thought I'd show my working. Could somebody guide me in the right direction?

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET