Search code examples
c#asp.net-core.net-coreasp.net-core-mvcasp.net-core-7.0

How do I get access to IMemoryCache in Program.cs in Asp.Net Core


I am in .Net 7.0 and in Program.cs we do not have any functions where there is a scope for dependency injection. The code is directly as follow:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyModel;
using WebMarkupMin.AspNetCore7;
using WordPressPCL;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();


// Add services to the container.
builder.Services.AddRazorPages();


var emailConfig = builder.Configuration
        .GetSection("EmailConfiguration")
        .Get<EmailConfiguration>();

builder.Services.AddSingleton(emailConfig);

//builder.Services.AddSitemap();

builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

I want to get access to IMemoryCache here and want to store some data in there. How do I do that?


Solution

  • You can do it with something like

    //Add memory cache
    builder.Services.AddMemoryCache();
    var app = builder.Build();
    
    //Get memory cache instance
    var cache = app.Services.GetRequiredService<IMemoryCache>();
    
    
    //Set a value in cache
    cache.Set("key", "value", new MemoryCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10000)
    });
    

    Simple working example

    Program.cs

    using Microsoft.Extensions.Caching.Memory;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    // Add memory cache
    builder.Services.AddMemoryCache();
    var app = builder.Build();
    
    // Get memory cache instance
    var cache = app.Services.GetRequiredService<IMemoryCache>();
    
    //Set a value in cache
    cache.Set("key", "value", new MemoryCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10000)
    });
    app.UseHttpsRedirection();
    app.UseSwagger();
    app.UseSwaggerUI();
    
    
    app.UseRouting();
    app.MapControllers();
    app.Run();
    

    ExampleController.cs

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Caching.Memory;
    
    namespace MemoryCache;
    
    [Controller]
    [Route("api/[controller]")]
    public class ExampleController : Controller
    {
        private readonly IMemoryCache _cache;
    
        public ExampleController(IMemoryCache cache)
        {
            _cache = cache;
        }
    
        // GET
        [HttpGet("{key}")]
        public IActionResult Index(string key)
        {
            return Json(_cache.Get(key));
        }
        [HttpPost]
        public IActionResult Create(string key, string value)
        {
            _cache.Set(key, value, new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10000)
            });
            return Ok();
        }
    }
    

    You could try it if you want Repo