Manage the lifetime of dbContext

asp.net-mvc-4 dbcontext entity-framework

Question

I would like to tie the lifetime of a dbContext to the lifetime of a session, to - for example - be able to commit or abandon changes on a group of mutations on the dbcontext over multiple requests.

Are there any other (better?) ways to accomplish this? If no, what would be a suitable mechanism to create and dispose of the contexts? I am thinking about static hashtables with cleanup on session end, but maybe I'm doing it All Wrong. I am also thinking about the idea of only holding on to those contexts that have to do work over multiple requests, and keeping the rest per action. Any advice?

1
12
10/30/2012 12:55:15 PM

Accepted Answer

You can use IoC(Inversion of Control) containers to manage the lifetime of DBContext such as StructureMap with following steps :

  1. Install nuget package for MVC 4 : http://nuget.org/packages/StructureMap.MVC4

  2. Read quick start : http://docs.structuremap.net/QuickStart.htm

  3. Set scope of your DBContext : http://docs.structuremap.net/Scoping.htm

Also you can use the combination of Repository and Unit Of Work Patterns for commit or abandon changes on a group of mutations on the dbcontext over multiple requests.

6
6/9/2013 6:33:35 AM

Popular Answer

This question is answered fairly elegantly in the following SO post:

StructureMap CacheBy InstanceScope.HttpSession not working

Essentially, the magic comes from the following code (adapted for your question and the newer syntax for StructureMap):

ObjectFactory.Initialize(factory => {
    factory.For<MyContext>()
           .CacheBy(InstanceScope.HttpSession)
           .Use(new MyContext(_myConnectionString));
});

Then - in your controller, simply create an instance of the object by using:

var db = ObjectFactory.GetInstance<MyContext>();

Because your IoC (Inversion of Control) set-up via StructureMap has configured the instances to be scoped to HttpSession, you should retrieve the same context each time as long as the session is the same.

However - bear in mind that with DbContext objects, in particular, this is usually a very poor idea - as you are mixing a state-tracking object with a stateless environment, and can easily get yourself into a state where a bad transaction or an object which is in an odd state can stop you from doing any further database calls until you refresh your session.

DbContext objects are generally designed to be extremely lightweight and disposable. It's fully ok to let them drop out of scope and die basically as soon as you're done with them.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow