【发布时间】:2020-06-11 10:57:24
【问题描述】:
如何在控制器中获取当前(按请求)IServiceScope 的实例?在服务中?
计划是用它来解析属于同一范围的服务。
【问题讨论】:
-
ctor(IServiceProvider scope) 代替
标签: c# asp.net-core dependency-injection asp.net-core-webapi
如何在控制器中获取当前(按请求)IServiceScope 的实例?在服务中?
计划是用它来解析属于同一范围的服务。
【问题讨论】:
标签: c# asp.net-core dependency-injection asp.net-core-webapi
在控制器中获取实例...:
没有必要在控制器中使用IHttpContextAccessor。已经有一个 HttpContext property 适合您。如果你想访问HttpContext,只需
// no need to use IHttpContextAccessor.HttpContext
var svc = HttpContext.RequestServices.GetService<MyService>();
或者作为替代方案,直接注入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");
}
特别是,如果所需服务的范围恰好是请求范围,只需将它们全部注入:
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 ?
一种解决方案是在控制器的构造函数中请求IHttpContextAccessor contextAccessor,然后从中解析所需的服务:
var svc = contextAccessor.HttpContext.RequestServices.GetService<MyService>();
【讨论】:
IHttpContextAccessor脱钩