每个请求的Windsor和DbContext - 已经处理了DbContext

时间:2014-05-22 07:19:47

标签: entity-framework castle-windsor dbcontext

我在HomeController中有一个方法,我试图通过URL访问,如下所示:

http://localhost/web/home/GetSmth

第一次运行,但刷新页面后,我收到此错误:

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

正如标题所述,我试图根据请求使用Castle Windsor和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);
        }
}

1 个答案:

答案 0 :(得分:4)

您正在使用默认生命周期注册ISomeService,即单身。一旦创建,它将继续使用相同的DbContext。最简单的解决方案是根据请求或瞬态更改其生命周期。

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