CacheService.cs


This is a very handy class using for easy caching if object does not exist, while executing handed function.

This can be overridden by URL-paramters like "forceReCache", which will clear cache key for all caches that page load. This means that it will recache all current objects.

You also have the "noCache" option, which means that all functions will be executed and bypass caching objects

Use it by calling: 

var result = CacheService.GetOrAdd("Cache_Key", () => FunctionToCall());

 

CacheService.cs

 

using System;
using System.Runtime.Caching;
using System.Web;
 
namespace MyCacheServiceNamespace
{
    public class CacheService
    {
        private static readonly ObjectCache Cache = MemoryCache.Default;
 
        public T GetOrAdd<T>(string key, Func<T> func, DateTime time) where T : class
        {
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["noCache"]))
            {
                return func();
            }
 
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["forceReCache"]))
            {
                Cache.Remove(key);
            }
 
            var value = Get<T>(key);
            if (value != null) return value;
            value = func();
 
            if (value == null)
            {
                //cant cache null.
                return null;
            }
 
            Cache.Add(key, value, time);
            return value;
        }
 
        public T GetOrAdd<T>(string key, Func<T> func) where T : class
        {
            return GetOrAdd(
              key,
              func,
              DateTime.Now.AddHours(1));
        }
 
        public void Remove(string key)
        {
            Cache.Remove(key);
        }
 
        public static bool Exists(string key)
        {
            return Cache.Get(key) != null;
        }
 
        public static T Get<T>(string key) where T : class
        {
            try
            {
                return (T)Cache[key];
            }
            catch
            {
                return null;
            }
        }
 
    }
}

 


Published: 2016-08-24