Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage the lifetime of dbContext

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?

like image 449
Martijn Avatar asked Oct 25 '12 11:10

Martijn


2 Answers

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.

like image 63
Mohsen Alikhani Avatar answered Sep 20 '22 18:09

Mohsen Alikhani


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.

like image 26
Troy Alford Avatar answered Sep 18 '22 18:09

Troy Alford