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

235 views Asked by At

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?

3

There are 3 answers

0
Vinicius Andrade On BEST ANSWER

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

3
Martin Staufcik On

One way would be to register MemoryCache as a singleton. It has advantages, all application cache is in one place.

var memoryCache = new MemoryCache(new MemoryCacheOptions());
builder.Services.AddSingleton<IMemoryCache>(memoryCache);
0
Ruikai Feng On

You may try:

public class MyMemoryCache
{
    public MyMemoryCache()
    {
        Cache = new MemoryCache(new MemoryCacheOptions());
        Cache.Set<string>("key", "val");
    }
    public MemoryCache Cache { get; } 
   
}


builder.Services.AddSingleton<MyMemoryCache>();


//get the value
var val=_myMemoryCache.Cache.Get("key");

follow this document