asp.net core 6+中获取IServiceProvider的几种途径,以及之间的区别

获取IServiceProvider实例的几种方法

  1. 通过构造函数注入(Constructor Injection):

    public class MyController : ControllerBase
    {
        private readonly IServiceProvider _serviceProvider;
    
        public MyController(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }
    }
    
  2. 通过builder.ServicesBuildServiceProvider方法获取:

    var serviceProvider = builder.Services.BuildServiceProvider();
    
  3. 通过WebApplication实例获取:

    WebApplication app = builder.Build();
    var serviceProvider = app.Services;
    
  4. 通过HttpContext获取:

    public class MyController : ControllerBase
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public MyController(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        public IActionResult Get()
        {
            var serviceProvider = _httpContextAccessor.HttpContext?.RequestServices;
            Return Ok();
        }
    }
    

几种方式之间的区别

特别是通过WebApplication获取的方式

通过WebApplication实例获取的serviceProvider,其作用域是跟随WebApplication的生命周期,及程序的生命周期,其可以解析到Singleton生命周期的服务,但是如果服务注册为Scoped,就会报错Cannot resolve scoped service from root provider,会引发服务的范围检查。

但是可以通过CreateScope方法,来获取带范围的serviceProvider,然后可正常获取到Scoped生命周期的服务。

using (var serviceScope = app.Services.CreateScope())
{
    var serviceProvider = serviceScope.ServiceProvider;
    var repository = serviceProvider.GetService<IRepository<SysUser>>();
}

posted @ 2024-01-04 21:32  小辫子啦啦啦  阅读(1294)  评论(0编辑  收藏  举报