private static string ExtractKeyFromExpression <TResult>(Expression <Func <TResult> > func) { string key; MethodCallExpression method = func.Body as MethodCallExpression; if (method == null) { throw new InvalidCachedFuncException("Body must be MethodCallExpression to auto generate a cache key"); } key = CacheKeyGenerator.GenerateKey(method); return(key); }
public static TResult FromCacheOrExecute <TResult>(FujiyBlogDatabase db, Expression <Func <TResult> > func, string key = null, MemoryCacheEntryOptions cacheItemPolicy = null, bool condition = true) { string lastDatabaseChangeAtDb = db.LastDatabaseChange; if (lastDatabaseChangeAtDb != lastDatabaseChange) { lastDatabaseChange = lastDatabaseChangeAtDb; ClearCache(); } if (!condition) { return(func.Compile()()); } if (func == null) { throw new ArgumentNullException("func"); } if (string.IsNullOrEmpty(key)) { MethodCallExpression method = func.Body as MethodCallExpression; if (method == null) { throw new InvalidCachedFuncException("Body must be MethodCallExpression to auto generate a cache key"); } key = CacheKeyGenerator.GenerateKey(method); } object returnObject = DefaultCache.Get(key); if (!(returnObject is TResult)) { returnObject = func.Compile()(); if (returnObject != null) { DefaultCache.Set(key, returnObject, cacheItemPolicy); } } return((TResult)returnObject); }