How can I cache objects in ASP.NET MVC?

后端 未结 8 1004
一生所求
一生所求 2020-12-04 06:25

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

相关标签:
8条回答
  • 2020-12-04 06:55

    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.

    0 讨论(0)
  • 2020-12-04 06:56

    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.

    0 讨论(0)
提交回复
热议问题