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
I like to hide the fact that the data is cached in the repository. You can access the cache through the HttpContext.Current.Cache property and store the User information using "User"+id.ToString() as the key.
This means that all access to the User data from the repository will use cached data if available and requires no code changes in the model, controller, or view.
I have used this method to correct serious performance problems on a system that was querying the database for each User property and reduced page load times from minutes to single digit seconds.
If you don't need specific invalidation features of ASP.NET caching, static fields are pretty good, lightweight and easy to use. However, as soon as you needed the advanced features, you can switch to ASP.NET's Cache
object for storage.
The approach I use is to create a property and a private
field. If the field is null
, the property will fill it and return it. I also provide an InvalidateCache
method that manually sets the field to null
. The advantage of this approach it that the caching mechanism is encapsulated in the property and you can switch to a different approach if you want.