我怎样才能在缓存ASP.NET MVC的对象? [英] How can I cache objects in ASP.NET MVC?

查看:92
本文介绍了我怎样才能在缓存ASP.NET MVC的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想缓存在ASP.NET MVC的对象。我有一个 BaseController ,我希望所有的控制器来继承。在BaseController有一个用户属性,只会抓住从数据库中的用户数据,这样我可以在控制器中使用它,或者把它传递给意见。

I'd like to cache objects in ASP.NET MVC. I have a BaseController that I want all Controllers to inherit from. In the BaseController there is a User property that will simply grab the User data from the database so that I can use it within the controller, or pass it to the views.

我想缓存此信息。我使用的每一个页面上的信息,所以没有必要去到数据库中每个页面请求。

I'd like to cache this information. I'm using this information on every single page so there is no need to go to the database each page request.

我想是这样的:

if(_user is null)
  GrabFromDatabase
  StuffIntoCache
return CachedObject as User

如何在ASP.NET MVC中实现简单的缓存?

How do I implement simple caching in ASP.NET MVC?

推荐答案

您仍可以使用存储缓存(所有响应之间共享)和会话(每个用户唯一的)。

You can still use the cache (shared among all responses) and session (unique per user) for storage.

我喜欢下面的尝试从缓存中获取/创建和存储模式(状伪code C#):

I like the following "try get from cache/create and store" pattern (c#-like pseudocode):

public static class CacheExtensions
{
  public static T GetOrStore<T>(this Cache cache, string key, Func<T> generator)
  {
    var result = cache[key];
    if(result == null)
    {
      result = generator();
      cache[key] = result;
    }
    return (T)result;
  }
}

你会使用这个像这样:

you'd use this like so:

var user = HttpRuntime
              .Cache
              .GetOrStore<User>(
                 string.Format("User{0}", _userId), 
                 () => Repository.GetUser(_userId));

您可以适应这种模式的会议,ViewState的(啊)或任何其他缓存机制。您还可以扩展ControllerContext.HttpContext(我认为这是在System.Web.Extensions程序的包装之一),或创建一个新的类一定空间嘲讽缓存来做到这一点。

You can adapt this pattern to the Session, ViewState (ugh) or any other cache mechanism. You can also extend the ControllerContext.HttpContext (which I think is one of the wrappers in System.Web.Extensions), or create a new class to do it with some room for mocking the cache.

这篇关于我怎样才能在缓存ASP.NET MVC的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆