Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache data in a MVC application

I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.

In my scenario I will be using LINQ to Entities (entity framework). On the first call to GetNames (or whatever the method is) I want to grab the data from the database. I want to save the results in cache and on the second call to use the cached version if it exists.

Can anyone show an example of how this would work, where this should be implemented (model?) and if it would work.

I have seen this done in traditional ASP.NET apps , typically for very static data.

like image 456
Coolcoder Avatar asked Dec 05 '08 13:12

Coolcoder


People also ask

How do I cache in MVC?

In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.

What is meant by caching in MVC?

Caching is used to improve the performance in ASP.NET MVC. Caching is a technique which stores something in memory that is being used frequently to provide better performance. In ASP.NET MVC, OutputCache attribute is used for applying Caching.

How output cache works in MVC?

The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.


1 Answers

Here's a nice and simple cache helper class/service I use:

using System.Runtime.Caching;    public class InMemoryCache: ICacheService {     public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class     {         T item = MemoryCache.Default.Get(cacheKey) as T;         if (item == null)         {             item = getItemCallback();             MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));         }         return item;     } }  interface ICacheService {     T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class; } 

Usage:

cacheProvider.GetOrSet("cache key", (delegate method if cache is empty)); 

Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

Example:

var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll()) 
like image 116
Hrvoje Hudo Avatar answered Sep 23 '22 05:09

Hrvoje Hudo