1

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?

6
  • 1
    You created two separate caches. They won't share any data, because they're separate. Use the same MemoryCache instance in both constructors. Commented Jun 18, 2021 at 12:42
  • @canton7 i would appreacite if you tell me how Commented Jun 18, 2021 at 12:45
  • 1
    Create the MemoryCache once, and make sure both of your controllers can access that same reference. Alternatively, use MemoryCache.Default Commented Jun 18, 2021 at 12:47
  • 1
    Or inject memory cache via DI and resolve it in controllers. Commented Jun 18, 2021 at 12:50
  • @canton7 i dont have access to Default Commented Jun 18, 2021 at 13:02

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.