An application cache helper class

CacheHelper class contains a few methods with generic object parameter.  There are 4 methods, Add, Clear, Exists and Get.

You can pass in value pairs into Add method to add to application cache.

And retrieve it by using Get method by passing the string key.

    public static class CacheHelper
    {
        public static void Add(T o, string key, DateTime expiry) where T : class
        {
            HttpContext.Current.Cache.Insert(
                key,
                o,
                null,
                expiry,
                System.Web.Caching.Cache.NoSlidingExpiration);
        }

        public static void Add(T o, string key) where T : class
        {
            HttpContext.Current.Cache.Insert(
                key,
                o,
                null,
                DateTime.Now.AddHours(1),
                System.Web.Caching.Cache.NoSlidingExpiration);
        }

        public static void Clear(string key)
        {
            if (Exists(key))
                HttpContext.Current.Cache.Remove(key);
        }

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

        public static T Get(string key) where T : class
        {
            try
            {
                return (T)HttpContext.Current.Cache[key];
            }
            catch
            {
                return null;
            }
        }

An example of using it,

I am reading the contract plans from repository and save into the application cache. Then check if it is in the cache before read the database again.

            const string key = "AllContractPlans";
            if (CacheHelper.Exists(key))
            {
                return CacheHelper.Get<List>(key);
            }
            else
            {
                var plans = _contractRepo.FindAll().ToList();
                CacheHelper.Add<List>(plans, key, DateTime.Now.AddMonths(2));
                return plans;
            }

Application cache can speed up you application, but please be mindful that cache is shared across the whole application. And the data in your database may change as well, in that case, you need to clear your cache when you modify you data against database.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s