5
我一直在寻找Caching在我的web api中,我可以使用一个api方法的输出(在12小时内改变一次),然后我发现this solution SO,但我有一个困难在了解和使用下面的代码web api中的内存缓存
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
}
我不知道如何调用,并在下面情况下使用这种方法吗? 我有一个方法获取
public IEnumerable<Employee> Get()
{
return repository.GetEmployees().OrderBy(c => c.EmpId);
}
,我想缓存获取和我的其他方法使用它GetEmployeeById(输出)或Search()
public Movie GetEmployeeById(int EmpId)
{
//Search Employee in Cached Get
}
public IEnumerable<Employee> GetEmployeeBySearchString(string searchstr)
{
//Search in Cached Get
}
@little它的GetFromCache方法 – 2014-10-28 14:07:36
@little应该叫valueFactory函数内你的资料库中完成的(它只会如果对象是不是在执行缓存)。看看我的回答,我没有调用存储库,而是直接调用上下文,只是用存储库替换上下文。 – 2014-10-28 14:15:22
@little我更新了示例中的GetMovieBySearchParameter方法,现在它正在使用存储库。 – 2014-10-28 14:23:19