robbanp
I'm the co-founder of this website and the tech lead. Follow me on: twitter.com/robertpohl
Blog

The Rob blog

I'm Robert Pohl, the creator and co-founder to ThatsToday. I blog mostly about technology and internet related topics. Follow me on Twitter @robertpohl
Subscribe to RSS

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

 

Comments on this article

Add your comment
Sign In

Not a member yet?

Signing up is FREE and will only take 15 seconds!

Facebook Login

Sign In

E-mail address:
Password:
Remember me
Sponsored links

Close