【问题标题】:Get current IServiceScope in controller获取控制器中的当前 IServiceScope
【发布时间】:2020-06-11 10:57:24
【问题描述】:

如何在控制器中获取当前(按请求)IServiceScope 的实例?在服务中?

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

【问题讨论】:

  • ctor(IServiceProvider scope) 代替

标签: c# asp.net-core dependency-injection asp.net-core-webapi


【解决方案1】:

在控制器中获取实例...

  1. 没有必要在控制器中使用IHttpContextAccessor。已经有一个 HttpContext property 适合您。如果你想访问HttpContext,只需

    // no need to use IHttpContextAccessor.HttpContext
    var svc = HttpContext.RequestServices.GetService<MyService>();
    
  2. 或者作为替代方案,直接注入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");
    }
    
  3. 特别是,如果所需服务的范围恰好是请求范围,只需将它们全部注入:

    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;
        }
    

【讨论】:

  • 为什么需要create a more small scope ?.. 为什么不直接sp.GetRequiredService
【解决方案2】:

一种解决方案是在控制器的构造函数中请求IHttpContextAccessor contextAccessor,然后从中解析所需的服务:

var svc = contextAccessor.HttpContext.RequestServices.GetService&lt;MyService&gt;();

【讨论】:

  • 还有更优雅的方式吗?我想将自己与IHttpContextAccessor脱钩
猜你喜欢
  • 2011-05-19
  • 1970-01-01
  • 2012-03-23
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多