Darren Lewis bio photo

Darren Lewis

Professional Nerd

Twitter GitHub StackOverflow
Published: July 19, 2010

I was looking for common data caching patterns recently and came across a rather simple but imo very elegant solution for caching on Stack Overflow. The source is below and I’ve included a link to ensure the original author gets full credit.

public class InMemoryCache: ICacheService {   public T Get<T>(string cacheID, Func<T>; getItemCallback) where T : class   {     T item = HttpRuntime.Cache.Get(cacheID) as T;     if (item == null)     {       item = getItemCallback();       HttpContext.Current.Cache.Insert(cacheID,item);     }     return item;   } }

As you can see this method takes as a second param a Func<T>; delegate that will be called if the requested item is not in the cache. So the call from my MVC Controller now looks like: model.Countries = _cacheService.Get( "countries>, () => _referenceDataRepository.GetCountries()); model.Genders = _cacheService.Get("genders",() => _referenceDataRepository.GetGenders()); model.Titles = _cacheService.Get("titles",() => _referenceDataRepository.GetTitles());

Original StackOverflow Post