Friday, February 27, 2009

Type safe web cache wrapper - ASP.NET

While building a URL mapping routine for my portal, I needed to optimize the loading of member specific URL keys.
For this I use the HttpContext.Current.Cache object that is easily used in the ASP.NET environment. Whats "ugly" with the Cache object is that it takes a object as a input parameter and of course return the cached object as the type of object.

So instead of do alot of type casting, I created a small wrapper class that use generics to handle the object types.

Take a look:


#region
using System;
using System.Web;
using System.Web.Caching;
#endregion
namespace Portal.PCache
{
/// <summary>
/// Type safe object cache
/// </summary>
public class ObjectCache
{
private const int TIMEOUT = 60;
/// <summary>
/// Adds the specified cache object. it will last for max 1hr from last access
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cacheObject">The cache object.</param>
/// <param name="keyName">Name of the key.</param>
public static void Add<T>(T cacheObject, string keyName)
{
HttpContext.Current.Cache.Insert(keyName, cacheObject, null, Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(TIMEOUT));

}


/// <summary>
/// Removes object with the specified key.
/// </summary>
/// <param name="key">The key.</param>
public static void Remove(string key)
{
HttpContext.Current.Cache.Remove(key);
}

/// <summary>
/// Check if object with the specified key exists.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>

public static bool Exist(string key)
{
return HttpContext.Current.Cache[key] != null;
}

/// <summary>
/// Gets the object with the specified key.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public static T Get<T>(string key) where T : class
{
return HttpContext.Current.Cache[key] as T;
}
}
}


And to use the class:



MyObject obj = new MyObject();
string key = "myobject1";

bool exists = ObjectCache.Exist(key);
if(!exists)
{
ObjectCache.Add<MyObject>(obj, key);
}

MyObject another = ObjectCache.Get<MyObject>(key);

3 comments:

Anonymous said...

Nice, could you also put the generic type T at the class-level, instead of at the method level? Then you'd only have to define your type once.

Neat idea. I like it.

Robert Pohl said...

Hi Carl, thanks for your comment!

You you could also define the class like this:

public class ObjectCache<T>...

But then you need to define T also on Exists<T>, which is not the sweetest solution. I'd prefere to define T only when I need to use T :)

Anonymous said...

robertpohl.blogspot.com is very informative. The article is very professionally written. I enjoy reading robertpohl.blogspot.com every day.
instant cash loans
payday loans