Skip to content

Instantly share code, notes, and snippets.

@mika76
Last active December 30, 2021 17:28
Show Gist options
  • Save mika76/767302594cffae6d582be7592eccbd82 to your computer and use it in GitHub Desktop.
Save mika76/767302594cffae6d582be7592eccbd82 to your computer and use it in GitHub Desktop.

From http://stackoverflow.com/a/349111/11421

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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment