问题描述
entity framework数据层,使用ninject进行注入,生命周期设置为InRequestScope,在过滤器中调用数据库时,会出现
The operation cannot be completed because the DbContext has been disposed.

原因分析
在SO上找到几个相关的问题,如下:
Filter Providers aren't created for every request and therefore aren't allowed to get any dependency in request scope.
其中3里面github是官方关于过滤器中使用注入的方式介绍,前面两个答案也基本是采用了这个方式。
解决方法
最终采用了上面1里面的,BZ的回答。
步骤
-
定义一个特性类,给要使用的控制器或者action打上相关标签
-
定义一个过滤器,该过滤器里使用构造函数的方式获取注入的实体对象并使用。我这里就是调用数据库的DbContext
-
使用如下方式进行绑定
this.BindFilter<MyAuthorizeFilter>(System.Web.Mvc.FilterScope.Controller, 0).WhenControllerHas<MyAuthorizeAttribute>();
网友评论