StructureMap is not disposing data context when using HttpContextScoped()

前端 未结 2 712
情歌与酒
情歌与酒 2020-12-31 14:11

My goal is to have one data context (MainDbContext) per HTTP request in ASP.NET MVC and dispose the data context when the request ends.

I\'m using the f

相关标签:
2条回答
  • 2020-12-31 14:37

    Instead of:

    x.For<MainDbContext>().HttpContextScoped();
    

    Try:

    x.For<MainDbContext>().HttpContextScoped().Use(() => new MainDbContext());
    

    Also normally it's repository classes that need a db context. So instead of ObjectFactory.GetInstance<MainDbContext>(); have your repositories take some interface db context and configure StructureMap to inject the MainDbContext into them. Then make StructureMap inject repositories into controllers, ...

    In Application_EndRequest:

    protected void Application_EndRequest()
    {
        ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
    }
    
    0 讨论(0)
  • 2020-12-31 14:49

    Using a nested container is the only way to get Structure Map to automatically dispose objects. If you're not using that technique the only way is to dispose the objects yourself using either the way the OP described (pulling the object from the container and disposing it; see this NHibernate example for one way to do it) or to scope the object to HttpRequest and call ReleaseAndDisposeAllHttpScopedObjects as Darin described.

    0 讨论(0)
提交回复
热议问题