温莎和DbContext每个请求 - DbContext已被处理

5

我在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个回答

4

您正在使用默认生命周期(singleton)注册 ISomeService。一旦创建,它就会继续使用相同的 DbContext 。最简单的解决方案是将其生命周期更改为 per request 或 transient。

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

1
这意味着所有使用DbContext的类(服务、存储库、查询对象等)都应该使用这个生命周期? - andree
@andree 这是真的。Castle Windsor甚至会在调试器中警告你,请检查一下。 - Ufuk Hacıoğulları

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接