Olá,
Eis um Cache Helper que en encontrei aqui https://stackoverflow.com/questions/343899/how-to-cache-data-in-a-mvc-application, que eu modifiquei para levar em conta não somente as classes mas qualquer tipo de dado.
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 eis como é utilizado, com o lambda o código fica elegante, não é mesmo ?
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); }); }