Manage the lifetime of dbContext

Martijn picture Martijn · Oct 25, 2012 · Viewed 9.4k times · Source

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?

Answer

Mohsen Alikhani picture Mohsen Alikhani · Nov 3, 2012

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.