VisualBean
12/1/2017 - 6:51 AM

CachingService.cs

public class CachingService<T> where T : class
{

    private int cacheExpirationInMinutes;
    private string keyPrefix;

    public CachingService(string keyPrefix, int cacheExpirationInMinutes)
    {
        this.keyPrefix = keyPrefix;
        this.cacheExpirationInMinutes = cacheExpirationInMinutes;
    }

    /// <summary>
    /// Get item from cache by key. If item is not found DoIfNotExist is executed and the results are added to the key.
    /// </summary>
    /// <param name="key">key of item in cache.</param>
    /// <param name="DoIfNotExist">execute if cache could not find key. the result of this function is added to the key.</param>
    /// <returns/><see cref="T"/></returns>
    public T GetOrDoIfNotExist(string key, Func<T> DoIfNotExist)
    {
        if ((key ?? "").Length <= 0)
        {
            return DoIfNotExist();
        }

        key = $"{keyPrefix}{key}";

        T result = HttpRuntime.Cache[key] as T;

        if (result == null)
        {
            result = DoIfNotExist();

            if (result == null)
            {
                HttpRuntime.Cache.Remove(key);
            }
            else
            {
                HttpRuntime.Cache.Add(key,
                result,
                null,
                DateTime.Now.AddMinutes(cacheExpirationInMinutes),
                Cache.NoSlidingExpiration,
                CacheItemPriority.Low,
                null);
            }
        }

        return result;
    }
}