locked
如何在Minimal Api中获得Scoped服务 RRS feed

  • 问题

  • 构建了一个基于.net 6的minimal api工程, 使用自带的IOC注入服务, 期望可以获得一个scoped的服务(即当前浏览器中用户获得同一个实例对象).

    实际结果:

    AddScoped表现没有达到预期, 和AddTransient的效果是一样的. 

    预期结果:

    用户在同一浏览器进程下访问endpoint获得递增的返回值, 在新浏览器进程下会获得重新从0开始的计数值.

    代码:

    https://github.com/ali50m/LifetimeTest

    复现步骤:

    1. git clone git@github.com:ali50m/LifetimeTest.git
    2. dotnet run --project .\LifetimeTest\
    3. 使用浏览器访问测试http://localhost:5123/swagger/index.html,或直接访问http://localhost:5123/test

    repro


    2022年9月13日 1:39

全部回复

  • 补充:

    测试过几种AddScoped的组合,均无法达到预期的需求. 如果使用AddSingleton则又不能达到分离用户进程.

    builder.Services.AddScoped<ICounter, Counter>();
    builder.Services.AddScoped<IFirstCounter, FirstCounter>();

    2022年9月13日 1:43