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:

Update
