如何在.NET 7的Program.cs中获取IMemoryCache并存储数据?
在.NET 7.0的Program.cs中获取IMemoryCache并存储数据
步骤1:确保IMemoryCache服务已注册
虽然.NET 7中调用AddControllersWithViews或AddRazorPages时,框架会自动注册IMemoryCache的单例实例,但为了确保万无一失,你可以手动添加注册代码:
// 在builder.Services相关配置中添加 builder.Services.AddMemoryCache();
步骤2:在Program.cs中获取IMemoryCache实例并操作缓存
完成服务注册并调用builder.Build()创建WebApplication实例后,你可以通过应用的服务提供者获取IMemoryCache,执行缓存存储操作,有两种常用方式:
方式一:直接获取单例IMemoryCache(适用于单例服务)
var builder = WebApplication.CreateBuilder(args); // 你的现有服务注册代码 builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); builder.Services.AddRazorPages(); // 手动添加MemoryCache注册(可选,确保服务存在) builder.Services.AddMemoryCache(); // 其他现有配置 var emailConfig = builder.Configuration .GetSection("EmailConfiguration") .Get<EmailConfiguration>(); builder.Services.AddSingleton(emailConfig); builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); // 构建应用 var app = builder.Build(); // 获取IMemoryCache实例 var memoryCache = app.Services.GetRequiredService<IMemoryCache>(); // 存储数据到缓存,设置30分钟过期 memoryCache.Set("CacheKey", "缓存内容", TimeSpan.FromMinutes(30));
方式二:创建临时服务作用域获取(更规范,兼容所有生命周期服务)
如果后续需要操作非单例服务,推荐使用这种方式:
var app = builder.Build(); // 创建临时服务作用域 using var scope = app.Services.CreateScope(); var scopeServices = scope.ServiceProvider; // 获取IMemoryCache实例 var memoryCache = scopeServices.GetRequiredService<IMemoryCache>(); // 存储数据,配置更精细的缓存策略 memoryCache.Set("CacheKey", "缓存内容", new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30), // 绝对过期时间 SlidingExpiration = TimeSpan.FromMinutes(10) // 滑动过期时间 });
注意事项
GetRequiredService<T>会在服务未注册时抛出异常,若不确定服务是否存在,可改用GetService<T>,它会返回null。- 缓存键需保证唯一性,避免与其他业务的缓存键冲突。
- 通过
MemoryCacheEntryOptions可灵活配置缓存的过期规则、优先级等参数。
内容的提问来源于stack exchange,提问作者K V Sharma
相关产品推荐
相关产品推荐

