Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put data in a MemoryCache on startup?

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?

like image 915
Simon Verbeke Avatar asked Nov 30 '16 13:11

Simon Verbeke


People also ask

How do I cache data in .NET Core?

ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server. Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache.

How do I use MemoryCache in .NET Core?

Implementing an In-Memory Cache Let's start by creating an ASP.NET Core Web API using the ASP.NET Core Web API with EF Core Code-First Approach. First, we inject the IMemoryCache and ILogger into the EmployeeController . Then, in the listing action method, we check if the employeeList data is available in the cache.


1 Answers

When you added the statement

services.AddMemoryCache();

you were in effect saying that you wanted a memory cache singleton that would get resolved wherever you injected IMemoryCache as you did in your controller. So instead of creating a new memory cache, you need to add values to the singleton object that was created. You can do this by changing your Configure method to something like:

    public void Configure(IApplicationBuilder app, 
        IHostingEnvironment env, 
        ILoggerFactory loggerFactory,
        IMemoryCache cache )
{
    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);
    //pipeline configuration
}
like image 52
GlennSills Avatar answered Sep 22 '22 14:09

GlennSills