Wednesday, 21 May 2014

Cache working using Asp.net MVC 4 application

Cache working using Asp.net MVC 4 application


Introduction

Here we learn how to use Cache to manage asp.net mvc application to reduce the database call.

Description

Here we learn how to use Cache to manage asp.net mvc application to reduce the database call. We used asp.net mvc 4 application to implement this cache management. 

Solution


Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Create one folder in your application called "Utilities" we will all customize .cs file in this folder. We called this management as Utilities of application.

Step 3 :  Add one class file in to you application name as "CacheManager.cs" or as per your acquirement.


Step 4 :  Now open that class file and make that class public and static for entire website after that there is no need to create object of that class file, we can directly access all function and property of this class.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;

namespace WebApplication1
{
    public static class CacheManager
    {
             
    }

}

Step 5 :  Add below code to that file for accessing Cache.

private static List<CountryList> _countryList;
        public static List<CountryList> CountryList
        {
            get
            {
                if (HttpContext.Current.Cache.Get("CacheManager.CountryList") == null)
                {
                    _countryList = null;
                }
                else
                {
                    _countryList = (List<CountryList>)HttpContext.Current.Cache.Get("CacheManager.CountryList");
                }

                return _countryList;
            }
            set
            {
                _countryList = value;
                HttpContext.Current.Cache.Remove("CacheManager.CountryList");
                HttpContext.Current.Cache.Add("CacheManager.CountryList", _countryList, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0), CacheItemPriority.Normal, null);
            }
        }

Step 6 :  Now access this cache object in your application for storing data and accessing data.

 public List<CountryList> GetCountries()
        {
            List<CountryList> countries = new List<CountryList>();
            if (CacheManager.CountryList == null)
            {
                CacheManager.CountryList = Query to get All country;
            }
            else
            {
                countries = CacheManager.CountryList;
            }
            return countries;
}

No comments:

Post a Comment

Thank you for your interest .