Can you please point me to an example. I want to cache some objects that will be frequently used in most of the pages on the website? I am not sure what will be the recommended way of doing it in MVC 6.
3 Answers
The recommended way to do it in ASP.NET Core is to use the IMemoryCache
. You can retrieve it via DI. For instance, the CacheTagHelper
utilizes it.
Hopefully that should give you enough info to start caching all of your objects :)

- 18,469
- 14
- 77
- 117

- 18,061
- 6
- 49
- 72
-
1Unfortunately this link now 404s – NikolaiDante Feb 03 '16 at 16:25
-
@NikolaiDante - That's because they changed the name to AspNetCore, https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.TagHelpers/CacheTagHelper.cs – Erik Funkenbusch Feb 03 '16 at 16:53
-
@ErikFunkenbusch ah, obviously. I've updated the post :-) – NikolaiDante Feb 03 '16 at 16:55
-
My current website is MVC 4 and I use DevTrends Donut[Hole]Caching. It would appear that the DonutHoleCaching is not necessary anymore because of the CacheTagHelper, is that true? – ganders Mar 28 '16 at 14:13
In startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
// Add other stuff
services.AddCaching();
}
Then in the controller, add an IMemoryCache
onto the constructor, e.g. for HomeController:
private IMemoryCache cache;
public HomeController(IMemoryCache cache)
{
this.cache = cache;
}
Then we can set the cache with:
public IActionResult Index()
{
var list = new List<string>() { "lorem" };
this.cache.Set("MyKey", list, new MemoryCacheEntryOptions()); // Define options
return View();
}
(With any options being set)
And read from the cache:
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
var list = new List<string>();
if (!this.cache.TryGetValue("MyKey", out list)) // read also .Get("MyKey") would work
{
// go get it, and potentially cache it for next time
list = new List<string>() { "lorem" };
this.cache.Set("MyKey", list, new MemoryCacheEntryOptions());
}
// do stuff with
return View();
}

- 18,469
- 14
- 77
- 117
-
3fyi, now it's services.AddMemoryCache() in startup.cs. Though like any pre-release software, this is subject to change again. – SergioL Jun 23 '16 at 22:18
I think currently there no such like OutputCache attribute available that avaiable in ASP.net MVC 5.
Mostly attribute is just shortcut and it will indirectly use Cache provider ASP.net.
Same thing available in ASP.net 5 vnext. https://github.com/aspnet/Caching
Here different Cache mechanism available and you can use Memory Cache and create your own attribute.
Hope this help you.

- 17,065
- 5
- 54
- 72