Home > Mobile >  .NET Core 3.1: Sharing lookup data between multiple requests
.NET Core 3.1: Sharing lookup data between multiple requests

Time:06-01

I have a .NET Core 3.1 app. I have some lookup tables that I want to read when the app starts and I want to cache the data, so that multiple request can share the same lookup data.

How can I do this?

How can I read the lookup tables at startup? Any example would be appreciated.

CodePudding user response:

I'm adding explanation, requested by user3552264.

How to use IMemoryCache?

  1. Add IMemoryCache singleton in Startup.cs: services.AddMemoryCache()
  2. Let inject IMemoryCache in your controller and use it in your method:
public class YourController 
{
    private readonly IMemoryCache memCache;
    private readonly ILookupTableSrc lookupTableSrc;

    public YourController(IMemoryCache memCache, ILookupTableSource lookupTableSrc) 
    { 
        this.memCache = memCache;
        this.lookupTableSrc = lookupTableSrc;
    }

    [HttpGet("LookupTable")]
    public async ActionResult<LookupTable> GetLookupTable(int tableId)
    {
        var lookupTable = memCache.Get<LookupTable>(tableId);
        if(lookupTable == null) 
        {
            var tableFromSrc = lookupTableSrc.GetById(tableId);
            lookupTable = memCache.Set(tableId, tableFromSrc);
        }
        return lookupTable;
    }
}

GetLookupTable(int tableId) retrieves lookupTable from memCache. If memCache is empty, you fill it by new object and it will be cached for next requests.

If you want to fill IMemoryCache in Startup.cs, please do it in existing Configure(...) method. As you see I added memCache and lookupTableSrc as parameters:

public void Configure(IApplicationBuilder app, IMemoryCache memCache, ILookupTableSrc lookupTableSrc)
{
    lookupTableSrc.GetAll().ForEach(lookupTbl => memCache.Set(lookupTbl.Id, lookupTbl);
}

CodePudding user response:

You can do this using a IMemoryCache. You don't have to do this necessarily at startup, you can also do this in the first request.

See the documentation

If you want to pre-populate the cache you can do so in an HostedService in the background.

  • Related