Home > Blockchain >  How to load data when .net core 6.0 web api app started?
How to load data when .net core 6.0 web api app started?

Time:05-17

I'd like to load file data into cache memory on program.cs(.net core 6.0) and loaded data will use in many services.

So I typed builder.Services.AddMemoryCache(); into source code.

But and then, I don't know how to use this memory cache in right there(in program.cs).

In the previous version, with Configure method and IMemoryCache cache parameter I can load data with memory cache like following code block

public void Configure(IMemoryCache cache)
{
    cache.set(...);
    cache.get(...);
}

I'm developing with .net core 6.0 web api. Does anybody know how to init data on program.cs in .net core 6.0?

CodePudding user response:

Below is a work demo, you can refer to it.

Option 1

Do it after the web host is built, in Program.cs:

...
builder.Services.AddMemoryCache();
var app = builder.Build();
var cache=app.Services.GetRequiredService<IMemoryCache>();
cache.Set("key1", "value1");
...

Option 2

Use a hosted service to intialize cache:

public class InitializeCacheService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        public InitializeCacheService (IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var cache = _serviceProvider.GetService<IMemoryCache>();

                cache.Set("key1", "value1");
            }

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }

In Program.cs, add below code:

builder.Services.AddMemoryCache();
builder.Services.AddHostedService<InitializeCacheService>();

ValuesController (Two options all use this controller)

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IMemoryCache _cache;
        public ValuesController(IMemoryCache cache)
        {
            _cache = cache;

        }
        [HttpGet("{key}")]
        public ActionResult<string> Get(string key)
        {
            //_cahce.Count is 0
            if (!_cache.TryGetValue(key, out var value))
            {
                return NotFound($"The value with the {key} is not found");
            }

            return value   "";
        }
    }

Result:

enter image description here

Update enter image description here

  • Related