Web api memory cache

I searched for Caching in my web api, where I can use the output of one api method (which changes once every 12 hours) for sequenceesnt calls, and then I found this solution in SO, but I find it difficult to understand and use the code below

private IEnumerable<TEntity> GetFromCache<TEntity>(string key, Func<IEnumerable<TEntity>> valueFactory) where TEntity : class { ObjectCache cache = MemoryCache.Default; var newValue = new Lazy<IEnumerable<TEntity>>(valueFactory); CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30) }; //The line below returns existing item or adds the new value if it doesn't exist var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<IEnumerable<TEntity>>; return (value ?? newValue).Value; // Lazy<T> handles the locking itself } 

I'm not sure how to call and use this method in the context below? I have a get method

  public IEnumerable<Employee> Get() { return repository.GetEmployees().OrderBy(c => c.EmpId); } 

and I want to cache Get output and use it in my other GetEmployeeById () or Search () methods

  public Movie GetEmployeeById(int EmpId) { //Search Employee in Cached Get } public IEnumerable<Employee> GetEmployeeBySearchString(string searchstr) { //Search in Cached Get } 
+5
c # asp.net-mvc asp.net-web-api memorycache asp.net-web-api2
Oct 27 '14 at 4:10
source share
1 answer

I updated your method to return classes instead of IEnumberable:

 private TEntity GetFromCache<TEntity>(string key, Func<TEntity> valueFactory) where TEntity : class { ObjectCache cache = MemoryCache.Default; // the lazy class provides lazy initializtion which will eavaluate the valueFactory expression only if the item does not exist in cache var newValue = new Lazy<TEntity>(valueFactory); CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30) }; //The line below returns existing item or adds the new value if it doesn't exist var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<TEntity>; return (value ?? newValue).Value; // Lazy<T> handles the locking itself } 

then you can use this method, for example:

 public Movie GetMovieById(int movieId) { var cacheKey = "movie" + movieId; var movie = GetFromCache<Movie>(cacheKey, () => { // load movie from DB return context.Movies.First(x => x.Id == movieId); }); return movie; } 

and for movie searches

 [ActionName("Search")] public IEnumerable<Movie> GetMovieBySearchParameter(string searchstr) { var cacheKey = "movies" + searchstr; var movies = GetFromCache<IEnumerable<Movie>>(cacheKey, () => { return repository.GetMovies().OrderBy(c => c.MovieId).ToList(); }); return movies; } 
+8
Oct 27 '14 at 8:22
source share



All Articles