Bry*_*isi 5 entity-framework ninject asp.net-mvc-3
我是EF和Ninject的新手,请原谅我,如果这没有意义:)
我有一个带有Ninject和Ninject.Web.Common引用的MVC3应用程序.我正在尝试将DbContext注入我的存储库.我所看到的是,在第一次请求时,一切都运行良好,但后续请求返回:
System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
Run Code Online (Sandbox Code Playgroud)
我的绑定:
kernel.Bind<ISiteDataContext>().To<SiteDataContext>().InRequestScope();
kernel.Bind<IProductRepository>().To<ProductRepository>();
kernel.Bind<IProductService>().To<ProductService>();
Run Code Online (Sandbox Code Playgroud)
我的服务类:
public class ProductService : IProductService {
[Inject]
public IProductRepository repository {get; set;}
...
}
Run Code Online (Sandbox Code Playgroud)
我的存储库类:
public class ProductRepository : IProductRepository {
[Inject]
public ISiteDataContext context {get; set;}
...
}
Run Code Online (Sandbox Code Playgroud)
我的SiteDataContext类:
public class SiteDataContext : DbContext, ISiteDataContext
{
static SiteDataContext()
{
Database.SetInitializer<SiteDataContext >(null);
}
public DbSet<Product> Products{ get; set; }
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
Run Code Online (Sandbox Code Playgroud)
我的控制器:
public class ProductController {
[Inject]
public IProductService productService {get; set;}
...
}
Run Code Online (Sandbox Code Playgroud)
如果我删除.InRequestScope(),那么它工作正常 - 但随后会导致Entity Framework出现问题,因为在数据上下文的多个单独实例中修改了对象.
当然,在发布点击我脑海中的东西之后不久,我就能解决这个问题.
问题在于,在MVC3中ActionFilters的行为发生了变化,我有一个注入了ProductService的过滤器.
我想过滤器处理了服务并最终丢弃了DbContext.
就我而言,解决方案很简单.我创建了第二个专门用于我的过滤器的DbContext.由于过滤器只是查询选择的几个表以验证对特定资源的授权,因此我不需要DbContext在单个请求中提供的工作单元上下文.我创建了一个使用新DbContext的新服务.在这种情况下,配置InTransientScope()就足够了