A common memory cache is provided by ASP.NET Core. You just need to inject it into each controller or other service where you want to access it. See the docs.
You need to ensure memory caching is registered, note this from the docs:
For most apps, IMemoryCache is enabled. For example, calling AddMvc,
AddControllersWithViews, AddRazorPages,
AddMvcCore().AddRazorViewEngine, and many other Add{Service} methods
in ConfigureServices, enables IMemoryCache. For apps that are not
calling one of the preceding Add{Service} methods, it may be necessary
to call AddMemoryCache in ConfigureServices.
To ensure this is the case, you add the registration within Startup.cs:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache();
...
Once memory caching is registered in Startup.cs, you can inject into any controller like this:
public class HomeController : Controller
{
private IMemoryCache _cache;
public HomeController(IMemoryCache memoryCache)
{
_cache = memoryCache;
}
...
Then use this _cache instance rather than using new to create one.
MemoryCacheinstance in both constructors.MemoryCacheonce, and make sure both of your controllers can access that same reference. Alternatively, useMemoryCache.Default