A day with .Net

My day to day experince in .net

Caching in ASP.NET MVC with Repository Pattern and WCF

Posted by vivekcek on June 25, 2014

In this post i will show you, how to implement caching in an asp.net mvc application.
This MVC application use repository pattern and consumes a WCF service.

1. Define an interface for our caching provider.

 public interface ICacheProvider
    {
        object Get(string key);
        void Set(string key, object data, int cacheTime);
        bool IsSet(string key);
        void Invalidate(string key);

    }

2. Implement this interface, dont forget to add reference for System.Runtime.Caching

 public class DefaultCacheProvider : ICacheProvider
    {
        private ObjectCache Cache { get { return MemoryCache.Default; } }

        public object Get(string key)
        {
            return Cache[key];
        }

        public void Set(string key, object data, int cacheTime)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);

            Cache.Add(new CacheItem(key, data), policy);
        }

        public bool IsSet(string key)
        {
            return (Cache[key] != null);
        }

        public void Invalidate(string key)
        {
            Cache.Remove(key);
        }
    }

3. In your repository add this code.

public class DVDRepository : IRepository
    {
        protected DVDStoreService.DVDServiceClient serviceClient;
        protected ICacheProvider cache;
        public DVDRepository(DVDStoreService.DVDServiceClient client, ICacheProvider cache)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            serviceClient = client;
            this.cache = cache;
        }

        public List<DVDStoreService.Movie> GetAll()
        {
            List<DVDStoreService.Movie> movies = cache.Get("movies") as List<DVDStoreService.Movie>;
            if (movies == null)
            {
                movies = serviceClient.GetAllData().ToList();
                cache.Set("movies", movies, 60);
            }
            return movies;
        }
      }
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