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