2014-05-22 55 views
4

我有一個方法在HomeController中,我試圖通過URL訪問,就像這樣:溫莎的DbContext每個請求 - 的DbContext已經佈置

它的工作原理
http://localhost/web/home/GetSmth 

第一次,但清爽的頁面後,我得到這個錯誤:

The operation cannot be completed because the DbContext has been disposed. 

正如標題狀態,我試圖使用溫莎城堡和每次的DbContext要求。

 public class Installer1 : IWindsorInstaller 
      { 
       public void Install(IWindsorContainer container, IConfigurationStore store) 
       { 
        container.Register(Classes.FromThisAssembly() 
            .BasedOn<IController>() 
            .LifestyleTransient()        
            ); 

        var connString = ConfigurationManager.ConnectionStrings["MainDbContext"].ConnectionString; 

        container.Register(Component.For<MainDbContext>().DependsOn(Property.ForKey("conn").Eq(connString)).LifeStyle.PerWebRequest); 
        container.Register(Component.For<ISomeService>().ImplementedBy<SomeService>()); 
       } 
} 

HomeController的是這樣的:

public class HomeController : Controller 
{ 
     private ISomeService _someService; 

     public HomeController(ISomeService someService) 
     { 
      _someService = someService;    
     } 

     public ActionResult Index() 
     {  
      return View(); 
     } 

     public JsonResult GetSmth() 
     { 
      var data = _someService.GetData().ToList(); 
      return Json(data, JsonRequestBehavior.AllowGet); 
     } 
} 

回答

3

正在註冊ISomeService與默認的生命週期,這是單身。一旦創建,它將繼續使用相同的DbContext。最簡單的解決方案是將其生命週期更改爲每個請求或瞬態。

container.Register(Component.For<ISomeService>() 
          .ImplementedBy<SomeService>() 
          .LifeStyle.PerWebRequest); 
+1

那麼這意味着所有使用DbContext(Services,Repositories,QueryObjects等)的類都應該使用這個生命週期? – andree

+0

@andree這是真的。溫莎城堡甚至警告過你,在調試器上檢查它。 –

相關問題