gpt4 book ai didi

c# - 获取 Controller 中的当前 IServiceScope

转载 作者:行者123 更新时间:2023-12-03 23:49:03 25 4
gpt4 key购买 nike

如何获得当前(按请求)IServiceScope 的实例在 Controller 中?在服务中?

计划是使用它来解析属于同一范围的服务。

最佳答案

get an instance ... in a controller:


  • 无需使用IHttpContextAccessor 内 Controller .已经有 HttpContext property 为你。如果您想访问HttpContext , 只是

    // no need to use IHttpContextAccessor.HttpContext
    var svc = HttpContext.RequestServices.GetService<MyService>();
  • 或者作为替代方案,注入(inject) IServiceProvider直接地:

    public class MyController : Controller
    {
    private IServiceProvider _sp;
    public MyController(IServiceProvider sp)
    {
    this._sp = sp;
    }
    }

    当你想要一个小范围时,你可以如下创建它:
    public IActionResult MyActoin()
    {
    // create a more small scope
    using (var scope = this._sp.CreateScope())
    {
    var sp = scope.ServiceProvider;
    // now you get the services from this small scope
    var svc1 = sp.GetRequiredService<MyService1>();
    var svc2 = sp.GetRequiredService<MyService2>();
    //...
    }
    return new JsonResult("it works");
    }
  • 特别是,如果所需服务的范围恰好是请求范围,只需将它们全部注入(inject):
    public class MyController : Controller
    {
    private IServiceProvider _sp;
    private readonly MyService1 _service1;
    private readonly MyService2 _service2;

    public MyController(IServiceProvider sp, MyService1 service1, MyService2 service2,...)
    {
    this._sp = sp;
    this._service1 = service1;
    this._service2 = service2;
    }
  • 关于c# - 获取 Controller 中的当前 IServiceScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60433066/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com