Salut,
Voici un Cache Helper que j'ai trouvé ici https://stackoverflow.com/questions/343899/how-to-cache-data-in-a-mvc-application, et que j'ai modifié pour prendre en compte tous les types de données et non seulement les classes.
public static class InMemoryCache { public static T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) { if (HttpContext.Current == null || HttpContext.Current.Cache == null) return getItemCallback(); bool cacheExists = HttpContext.Current.Cache[cacheKey] != null; T item; if (cacheExists) item = (T)HttpContext.Current.Cache[cacheKey]; else { item = getItemCallback(); if (item != null) HttpContext.Current.Cache.Insert(cacheKey, item, null, DateTime.UtcNow.AddDays(1), Cache.NoSlidingExpiration); } return item; } }
Et voilà comment on l'utilise, en utilisant une expression lambda, c'est du code élégant, non ?
public static Dictionary<string, string> getTipsCategory() { return InMemoryCache.GetOrSet("getTipsCategory", () => { return db .BlogCategory .Where(c => c.BlogEntry.Count() > 0) .ToDictionary(c=>c.Name, c=>c.url); }); }