简体   繁体   中英

Caching a collection of lists in MVC

I am working on a search page that contains several dropdowns with distinct database values. I began researching caching techniques and ran across a few possible solutions

  1. OutputCaching
  2. HttpContext.Cache

As I read more into different types of caching, I remembered that this application also provides metrics pages, which can utilize the same dropdown menus from the search page. Now instead of a search page solution, I want a site wide solution.

The way I retrieve distinct values in both cases are nearly identical. I have a ViewModel with various "Available" fields. Those fields are populated in the constructor.

public class SearchViewModel
{
    public AvailableSites {set;get;}

    public SearchViewModel()
    {
        AvailableSites = db.SomeTable.Select(s => s.Site).Distinct();
    }
}

When my model is set up this way, every time a user hits a search or metrics page, the application must hit the database to populate the dropdown menus. Caching would greatly reduce the load it puts on the db and network.

It seems that OutputCache only works with controller actions, so that seems out of the question.

The result of the distinct query will change very rarely. Is this something I want to cache using HttpContext? What type of caching would work best in this case?

Also, what would be the best way to integrate this into my MetricBase (Each metric VM inherits from this) and SearchViewModel? Inheritance almost seems like overkill for this situation. Would I just include the class as such private AvailableValue Values {set;get;} and access them via Values.AvailableSites ?

System.Runtime.Caching.MemoryCache provides a robust in-memory cache (see http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.100).aspx ).

From what I understand, it was based on System.Web.Caching, but without the dependency on the System.Web assembly, so you can put it in your business layer.

This blog post should help you with implementation: http://deanhume.com/Home/BlogPost/object-caching----net-4/37

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM