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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments