LearnFast.Ninja

ASP.NET get cache object generic method example

In this example we create a static cache manager class with a generic method that also return generic and we also pass function as parameter. This is complex code but it is very flexible. In order to use cache object in class you need to get it from HttpContext Current.

Step 1: Create CacheManager class in your project and add the Fill From Cache or Db method. 

public static class CacheManager

{

    /// <summary>

    /// If the object exist in cache get it from the cache,

    /// else get the object from the database and fill the cache.

    /// T stand for Type.

    /// </summary>

    /// <example>

    /// List<Product> Products_List = CacheManager.Get_From_Cache_or_Db<List<Product>>(CacheKeys.All_Products, DataAccess.Get_All_Products);

    /// </example>

    public static T Get_From_Cache_or_Db<T>(string Cache_Key, Func<T> MethodName)

    {

        if (HttpContext.Current.Cache[Cache_Key] == null)

        {

            T tempT = MethodName();

            HttpContext.Current.Cache[Cache_Key] = tempT;

            return tempT;

        }

        else

        {

            return (T)HttpContext.Current.Cache[Cache_Key];

        }

    }

}


Step 2: This is how you use the function.

List<ProductProducts_List CacheManager.Get_From_Cache_or_Db<List<Product>>(CacheKeys.All_Products, DataAccess.Get_All_Products);



Tags

asp.net

cachemanager cache-manager cache httpcontext current cachekeys generic t