Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IMemoryCache does not save data at application startup

I created a fresh ASP.NET Core Web API project. Here is ConfigureServices in Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddMemoryCache();
        var serviceProvider = services.BuildServiceProvider();
        var cache = serviceProvider.GetService<IMemoryCache>();

        cache.Set("key1", "value1");
        //_cahce.Count is 1
    }

As you see I add an item to IMemoryCache. Here is my 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 + "";
    }
}

When I request https://localhost:5001/api/values/key1, the cache is empty and I receive a not found response.

like image 767
Seyed Morteza Mousavi Avatar asked Dec 01 '25 04:12

Seyed Morteza Mousavi


1 Answers

In short, the cache instance you're setting the value in is not the same as the one that is later being retrieved. You cannot do stuff like while the web host is being built (i.e. in ConfigureServices/Configure. If you need to do something on startup, you need to do it after the web host is built, in Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        var cache = host.Services.GetRequiredService<IMemoryCache>();
        cache.Set("key1", "value1");

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
 }
like image 149
Chris Pratt Avatar answered Dec 02 '25 18:12

Chris Pratt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!