【代码】.net core手动获取注入的对象

2023-02-13 11:02:20  阅读 1899 次 评论 0 条

1、在控制器:通过HttpContext来获取(反正你能拿到HttpContext,用它没问题,我这里是通过Attribute拦截拿到的)

IOptions<ApiConfig> options = HttpContext.RequestServices.GetService(typeof(IOptions<ApiConfig>)) as IOptions<ApiConfig>;
ApiConfig config= options.Value;

2、在ConfigureService:如果你这里使用了EF并且EF用的是DI获取的,在这里获取的时候,需要在EF的配置下面。

var provider = services.BuildServiceProvider();
IOptions<ApiConfig> userDAL = provider.GetService<IOptions<ApiConfig>>();

3、在Configure中

IArticleDAL articleDAL = app.ApplicationServices.GetService(typeof(IArticleDAL)) as IArticleDAL;

但是,如果对象使用的是Scope方式注入的,那么就会报错

Cannot resolve 'XXX.IArticleDAL' from root provider because it requires scoped service 'XXX.CNBLOGContext'.

需要进行CreateScope

//手动获取依赖注入对象
IServiceScope serviceScope = app.ApplicationServices.CreateScope();IArticleDAL articleDAL2 = serviceScope.ServiceProvider.GetService<IArticleDAL>();

4、View页面中:可以通过@Context来拿到HttpContext对象,后面和第一个一样了

@Context.RequestServices.GetService(typeof(XXX.Main.DAL.IBlogSetDAL))


最后附上我自己的一个示例,在ActionFilterAttribute拦截中拿到依赖注入的对象

public override void OnActionExecuting(ActionExecutingContext context)
        {
            //base.OnResultExecuting(context);
            IOptions<ApiConfig> options = context.HttpContext.RequestServices.GetService(typeof(IOptions<ApiConfig>)) as IOptions<ApiConfig>;
            ApiConfig config= options.Value;


        }



微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2225
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?