.NET点滴:说说Middleware构造中获取不到Scoped服务的问题

  “为什么中间件的构造函数里不能使用scope的生命周期类型啊?”,

  那就用实例来得到答案吧,先看小桂说的情况,是报错的:

复制代码
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<ITestService, TestService>();
var app = builder.Build();

app.UseMiddleware<TestMiddleware>();

app.MapGet("/djy", () =>
{
    Console.WriteLine("打酱油!");
    return "OK";
});

app.Run();

public interface ITestService
{
    void Print();
}
public class TestService : ITestService
{
    public TestService()
    {
        Console.WriteLine($"Time:{DateTime.Now},ToDo:TestService.ctor");
    }
    public void Print()
    {
        Console.WriteLine($"Time:{DateTime.Now},ToDo:TestService.Print");
    }
}
public class TestMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ITestService _testService;
    //正确姿势
    //public TestMiddleware(RequestDelegate next)
    
    public TestMiddleware(RequestDelegate next, ITestService testService)
    {
        Console.WriteLine($"Time:{DateTime.Now},ToDo:TestMiddleware.ctor");
        _next = next;
        _testService = testService;
    }
    //正确姿势
    //public async Task InvokeAsync(HttpContext context, ITestService testService)
        
    public async Task InvokeAsync(HttpContext context)
    {
        _testService.Print();
        await _next(context);
    }
}
复制代码

看报错:

  但如果把Service注入换成AddTransient就没有问题,这是为什么呢?

  官网有一段话:“Middleware is constructed at app startup and therefore has application life time. Scoped lifetime services used by middleware constructors aren't shared with other dependency-injected types during each request. ……”,这段话挑重点,就是中间件是服务启动时初始化,整个生命周期构造只调用一次,而AddScoped是每个对象实例化,DI就会创建一份,可以说Scoped的颗粒度更小,所以就不能在中件间的构造函数中出现(构造只有在初始化的时候调用到)。所以Scoped的Service放在InvokeAsync的参数中,因为InvokeAsync是每次请求时才调用到,和Scoped的颗粒度是一样的,所以这就是:“为什么中间件的构造函数里不能使用scope的生命周期类型啊?”的答案。

  想要更快更方便的了解相关知识,可以关注微信公众号 
posted @   刘靖凯  阅读(80)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示