I have a pretty unnecessary dilemma. I am lazily looking for a function that converts a lamda expression to a string. It bothers me that every time I type this cache key, but I do not want to waste time creating it.
I want to use it for the caching function I created:
Where would I like to get a name for a person without calling a function every time.
public static string GetPersonName(int id) { return Repository.PersonProvider.Cached(x => x.GetById(id)).Name; }
GetExpressionDescription will return "PersonProvider.GetById (int 10)"
I believe this is possible, but I wonder if anyone has already built it or seen it somewhere.
public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, double hours = 24) { var expressionDescription = GetExpressionDescription(function); return Cached(function, expressionDescription, hours); } public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, string cacheName, double hours = 24) { var context = HttpContext.Current; if (context == null) return function.Compile().Invoke(obj); R results = default(R); try { results = (R)context.Cache[cacheName]; } catch { } if (results == null) { results = function.Compile().Invoke(obj); if (results != null) { context.Cache.Add(cacheName, results, null, DateTime.Now.AddHours(hours), Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } } return results; }
source share