First of all, MemoryCache is part of the System.Runtime.Caching . It can be used by MVC applications, but this is not limited to MVC applications.
NOTE. There is also a System.Web.Caching (much older) that can only be used with ASP.NET infrastructure (including MVC).
Should / should it be used to load static information for retention in repeated calls?
Yes.
Should / should it be used to store data in the presentation of several action methods?
Yes. If your views use the same data, they can. If you have data that is on your _Layout.cshtml page that requires caching, you can do this in a global filter.
What happens if I have multiple users on the same page using the same MemoryCache?
The default caching is used by all users. It is specifically designed to store data in memory, so it does not need to be retrieved from the database for each request (for example, a list of state names on the verification page to populate a drop-down list for all users).
It is also recommended that you cache data that often changes for a second or two to prevent the flow of simultaneous requests from a denial of service attack in your database.
Caching is dependent on a unique key. You can store individual user data in the cache by creating a username or identification part of the key.
var key = "MyFavoriteItems-" + this.User.Identity.Name;
Warning: This method only works if you have one web server. It will not scale for multiple web servers. Session state (designed to store individual user memory) is a more scalable approach. However, the state of the session is not always worth the compromise .
Typical Caching Pattern
Note that although MemoryCache is thread safe, using it in conjunction with a database call can result in cross-threading operations. Without blocking, it is possible that you can receive multiple database queries to reload the cache when it expires.
So you should use the double-checked locking pattern to provide only one thread to reload the cache from the database.
Let's say you have a list that is wastefully appropriate for every request, because every user needs a list when they get to a specific page.
public IEnumerable<StateOrProvinceDto> GetStateOrProvinceList(string country) {
To cache the result of this query, you can add another method with a double-check lock pattern and use it to call the original method.
NOTE. . A common approach is to use a decorator pattern to make caching without problems with your API.
private ObjectCache _cache = MemoryCache.Default; private object _lock = new object();
So, you call GetCachedStateOrProvinceList and it will automatically get the list from the cache and, if it is not cached, it will automatically load the list from the database into the cache. Only one thread is allowed to call the database, the rest will wait until the cache is full, and then return the list from the cache when it is available.
Please note that the list of states or provinces for each country will be cached individually.