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?
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):
you'd use this like so:
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.
A couple of the other answers here don't deal with the following:
This could lead to the generator (which could take a long time) running more than once in different threads.
Here's my version that shouldn't suffer from this problem: