Last active
December 24, 2015 05:49
-
-
Save keith9820/6752574 to your computer and use it in GitHub Desktop.
C# caching object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.Caching; | |
namespace Application.Caching | |
{ | |
public static class RepoCache | |
{ | |
static ObjectCache cache = MemoryCache.Default; | |
public static bool UseCache | |
{ | |
get | |
{ | |
#if (DEBUG) | |
return false; | |
#else | |
return true; | |
#endif | |
} | |
} | |
public static T Retrieve<T>(string methodName, Func<T> fetchData, params object[] arguments) where T : class | |
{ | |
var cacheKey = GenerateCacheKey(methodName, arguments); | |
var result = cache[cacheKey] as T; | |
if(result != null) | |
return result; | |
return Add<T>(fetchData(), cacheKey); | |
} | |
private static T Add<T>(T item, string cacheKey) where T : class | |
{ | |
if (UseCache && item != null) | |
{ | |
var i = item as System.Collections.ICollection; | |
if (i != null) //if this is a collection type | |
{ | |
if (i.Count == 0) //don't cache empty collections | |
return item; | |
} | |
cache.Set(cacheKey, item, null, null); | |
} | |
return item; | |
} | |
private static string GenerateCacheKey(string methodName, params object[] arguments) | |
{ | |
if (arguments == null || arguments.Length == 0) | |
return methodName; | |
return string.Format("{0}~{1}", methodName, String.Join("~", arguments)); | |
} | |
} | |
} | |
/* EXAMPLE: | |
public User GetUser(int id) | |
{ | |
return RepoCache.Retrieve<User>("GetUser", () => | |
{ | |
using (var context = new DNSEntities()) | |
{ | |
return (from c in context.Users select c where c.id=id).FirstOrDefault(); | |
} | |
}, id); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment