You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Minimal API中如何正确注入使用IMemoryCache

ASP.NET Core Minimal API 中使用 IMemoryCache 的实现方法

Minimal API 没有传统控制器的类构造函数注入入口,你遇到的命名空间报错是因为直接把类字段写在了命名空间层级——C# 语法要求字段、方法必须定义在类/结构体/记录等类型内部,不能直接裸露在命名空间下。
正确实现步骤如下:

1. 先注册内存缓存服务

和传统MVC/控制器项目一致,首先在Program.cs的服务配置阶段注册内存缓存:

var builder = WebApplication.CreateBuilder(args);
// 注册内存缓存相关服务
builder.Services.AddMemoryCache();

var app = builder.Build();

2. 选择合适的方式注入并使用IMemoryCache

Minimal API 支持两种最常用的注入方式,不需要额外定义控制器类:

  • 方式1:路由处理方法参数直接注入(推荐)
    这是Minimal API最简便的写法,直接把IMemoryCache作为路由委托的参数传入即可,框架会自动从DI容器解析实例,不需要手动定义类字段:
app.MapGet("/demo", (IMemoryCache cache) =>
{
    // 读取缓存
    var cachedData = cache.Get<string>("demoKey");
    if (cachedData == null)
    {
        // 缓存不存在时写入,设置10分钟过期
        cachedData = "这是缓存的测试数据";
        cache.Set("demoKey", cachedData, TimeSpan.FromMinutes(10));
    }
    return Results.Ok(cachedData);
});
  • 方式2:封装到自定义处理类(适合复杂业务场景)
    如果业务逻辑比较复杂,不想把所有代码都堆在Program.cs的路由委托里,可以完全沿用传统控制器的构造函数注入写法,单独定义业务处理类:
// 单独定义的缓存处理类,构造函数注入和控制器完全一致
public class CacheBusiness
{
    private readonly IMemoryCache _cache;

    public CacheBusiness(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IResult GetDemoData()
    {
        var data = _cache.Get<string>("demoKey");
        // 其他复杂业务逻辑...
        return Results.Ok(data);
    }
}

然后在Program.cs中注册这个处理类,再映射路由即可:

// 把处理类注册到DI容器
builder.Services.AddScoped<CacheBusiness>();

// 路由映射时通过[FromServices]解析处理类实例
app.MapGet("/demo", ([FromServices] CacheBusiness business) => business.GetDemoData());

注意:不要直接在顶级语句块中通过根容器app.Services手动解析IMemoryCache实例长期持有,这种写法容易触发服务生命周期校验错误,也可能导致内存泄漏,优先使用上述两种参数注入的方式,框架会自动管理服务的释放和生命周期。

内容的提问来源于stack exchange,提问作者EyeSeeSharp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 18:39:55