14

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 3

15

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

fyi, now it's services.AddMemoryCache() in startup.cs. Though like any pre-release software, this is subject to change again.
15

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 :)

4 Comments

Unfortunately this link now 404s
@NikolaiDante - That's because they changed the name to AspNetCore, github.com/aspnet/Mvc/blob/dev/src/…
@ErikFunkenbusch ah, obviously. I've updated the post :-)
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?
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.