At startup, I want to create a store of static data for my web app. So I eventually stumbled onto Microsoft.Extensions.Caching.Memory.MemoryCache. After building the feature that uses the MemoryCache, I suddenly find the data I stored is not available. So they're probably two separate instances.
How do I access the MemoryCache instance in Startup that will be used by the rest of my web app? This is how I'm currently trying it:
public class Startup
{
public Startup(IHostingEnvironment env)
{
//Startup stuff
}
public void ConfigureServices(IServiceCollection services)
{
//configure other services
services.AddMemoryCache();
var cache = new MemoryCache(new MemoryCacheOptions());
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
//Some examples of me putting data in the cache
cache.Set("entryA", "data1", entryOptions);
cache.Set("entryB", data2, entryOptions);
cache.Set("entryC", data3.Keys.ToList(), entryOptions);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//pipeline configuration
}
}
And the Controller where I use the MemoryCache
public class ExampleController : Controller
{
private readonly IMemoryCache _cache;
public ExampleController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet]
public IActionResult Index()
{
//At this point, I have a different MemoryCache instance.
ViewData["CachedData"] = _cache.Get("entryA");
return View();
}
}
If this is not possible, is there perhaps a better/simpler alternative? Would a global Singleton work in this situation?