如何在MVC应用程序中缓存数据我在MVC应用程序中阅读了很多关于页面缓存和部分页面缓存的信息。但是,我想知道您将如何缓存数据。在我的场景中,我将使用LINQto实体(实体框架)。在第一次调用GetNames(或任何方法)时,我想从数据库中获取数据。我希望将结果保存在缓存中,并在第二次调用时使用缓存版本(如果存在的话)。有人能给我们举一个例子,说明它是如何工作的,应该在什么地方实现(模型?)如果能成功的话。我在传统的ASP.NET应用程序中看到过这种情况,通常用于非常静态的数据。
3 回答
炎炎设计
TA贡献1808条经验 获得超4个赞
using System.Runtime.Caching; public class InMemoryCache: ICacheService{
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
{
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
{
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
}
return item;
}}interface ICacheService{
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;}用法:
cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));例子:
var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())添加回答
举报
0/150
提交
取消
