Asp.net-mvc – How to cache objects in ASP.NET MVC

asp.net-mvccaching

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.

I'd like something like:

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

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

Best Answer

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

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>(
                 $"User{_userId}", 
                 () => Repository.GetUser(_userId));

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.