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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With