我在我的 web api 中寻找缓存,在那里我可以使用一个 api 方法的输出(在 12 小时内更改一次)进行后续调用,然后我在 SO 上找到了这个解决方案,但我很难理解和使用下面的代码
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
}
我不确定如何在以下上下文中调用和使用此方法? 我有一个方法 Get
public IEnumerable<Employee> Get()
{
return repository.GetEmployees().OrderBy(c => c.EmpId);
}
我想缓存 Get 的输出并在我的其他方法 GetEmployeeById() 或 Search() 中使用它
public Movie GetEmployeeById(int EmpId)
{
//Search Employee in Cached Get
}
public IEnumerable<Employee> GetEmployeeBySearchString(string searchstr)
{
//Search in Cached Get
}