Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windsor and DbContext per request - DbContext has been disposed

I have a method in HomeController, that I'm trying to access through URL, like this:

http://localhost/web/home/GetSmth

First time it works, but after refreshing page, I get this error:

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

As the title states, I'm trying to use Castle Windsor and DbContext per request.

       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 looks like this:

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);
        }
}
like image 656
andree Avatar asked Sep 30 '22 18:09

andree


1 Answers

You are registering ISomeService with the default lifecycle, which is singleton. Once it's created, it will keep using the same DbContext. Simplest solution is to change its lifecycle to per request or transient.

container.Register(Component.For<ISomeService>()
                            .ImplementedBy<SomeService>()
                            .LifeStyle.PerWebRequest);
like image 71
Ufuk Hacıoğulları Avatar answered Dec 31 '22 21:12

Ufuk Hacıoğulları