简体   繁体   中英

Can't access memory cache - ASP.NET Core

I want to store my data in memory cache and access it from another controller,what i have done is

 MemoryCache myCache = new MemoryCache(new MemoryCacheOptions());
 //responseQID is my data i have already seen it contains data 
 myCache.Set("QIDresponse", responseQID);

in another controller i want to get this data:

 MemoryCache myCache = new MemoryCache(new MemoryCacheOptions());
       var inmemory= myCache.Get("QIDresponse");

inmemory is null, where am I doing wrong?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM