How one could get an instance of the current (per-request) IServiceScope in a controller? In a service?
The plan is to use it to resolve services that belongs to the same scope.
How one could get an instance of the current (per-request) IServiceScope in a controller? In a service?
The plan is to use it to resolve services that belongs to the same scope.
get an instance ... in a controller:
There're no need to use IHttpContextAccessor within a Controller. There's already a HttpContext property for you. If you want to access HttpContext, just
// no need to use IHttpContextAccessor.HttpContext
var svc = HttpContext.RequestServices.GetService<MyService>();
Or as an alternative, inject the IServiceProvider directly:
public class MyController : Controller
{
private IServiceProvider _sp;
public MyController(IServiceProvider sp)
{
this._sp = sp;
}
}
and when you want a small scope, you can create it as below:
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");
}
In particular, if the required service's scope is exactly the Request Scope, just inject them all:
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;
}
One solution is to ask for IHttpContextAccessor contextAccessor in controller's constructor and then resolve the desired services from it:
var svc = contextAccessor.HttpContext.RequestServices.GetService<MyService>();