Using .NET Cache with MemoryCache
In this recipe, we will learn how to use the default Cache object in ASP.NET Core to cache CLR objects.
Getting ready
We will create an empty ASP.NET Core web application running on .NET Framework with VS 2017.
How to do it...
- First, we import the following dependency to be able to use caching in ASP.NET Core applications:
"Microsoft.Extensions.Caching.Memory": "2.0.0"
- Next, we import the MVC dependency:
"Microsoft.AspNetCore.Mvc": "2.0.0"
- We can now add the cache middleware:
public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
- Next, we create two folders at the project root,
Controllers
andViews
. - We then createÂ
HomeController.cs
 by right-clicking on theControllers
directory and selecting...