4

我有一个MVC4 web项目,并使用Castle Windsor作为我的DI容器。另外,我正在使用实体框架来访问SQL数据库。我想将我的生活方式设置为PerWebRequest,但是,当我这样做时,出现以下错误:“操作无法完成,因为DbContext已被处置”。依赖注入 - EF库快速调用方法

如果我使用瞬态生活方式,错误被忽略了,但它引入了一组新的问题与实体框架。我如何保持PerWebRequest的生活方式,但在调用dispose方法时是否正确?

我正在使用构造函数注入来传递我的存储库连接字符串来构建新的上下文。我也执行IDisposable。见下:

public class MySqlRepository : MyRepository, IDisposable 
{ 
    private readonly DbContext _context; 

    public MySqlRepository(string connectionString) 
    { 
     _context = new DbContext(connectionString); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if (disposing) 
     { 
      _context.Dispose(); 
     } 
    } 

    public void Dispose() 
    { 
     Dispose(true); 
    } 
} 
+1

该代码似乎是正确的。您确定使用SqlRepository的组件也具有PerWebReuquest或更短的生活方式吗? – Marwijn

回答

0

将所有注册的组件更改为使用PerWebRequest的生活方式后,我认为我的问题源于IEnumerable与实体框架的使用。这是一个非常类似于我的问题。 stackoverflow.com/questions/9691681/ ......我认为这是生活方式,但它可能与我如何与EF互动。

如果IEnumerable <>,通过调用.ToList()方法返回任何类型的存储库方法,我能够保留对Lifestyle.PerWebRequest的使用。这确保了我需要访问的数据将在上下文处理之前加载到内存中。

0

这应该不是问题。 我曾经遇到这个问题,原因是我的容器设置不正确。

这是一个使用城堡温莎工作的演示。

容器设置是这样的:

container = new WindsorContainer(); 
container.Register(Classes.FromThisAssembly().BasedOn<Controller>().LifestylePerWebRequest()); 
container.Register(Classes.FromThisAssembly().InNamespace("MvcIoCDemo.Models").WithServiceDefaultInterfaces().LifestylePerWebRequest()); 

控制器:

public class ProductsController : Controller 
{ 
    private readonly IProductRepository productRepository; 

    public ProductsController(IProductRepository productRepository) 
    { 
     if (productRepository == null) throw new ArgumentNullException("productRepository"); 
     this.productRepository = productRepository; 
    } 

库:

public class ProductRepository : IDisposable, IProductRepository 
{ 
    private readonly DemoDbContext context; 

    public ProductRepository() 
    { 
     context = new DemoDbContext(); 
    } 

见演示项目位置: https://github.com/kobbikobb/MvcIoCDemo