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);

No comments:

Post a Comment