Where should I create my Entity Framework context object in an MVC application?

I would like to use the Session-per-request template, as is often done when using NHibernate in ASP.NET.

My first thought was to put the code in a context in the BeginRequest event handler in Global.asax, but I found that this event fires not only for the initial request, which actually performs this work, but also for subsequent requests for static files. such as CSS and images.

I don’t want to create a whole bunch of additional contexts when they are not needed, so is there a way I can just run my code on the initial request and not on static files?

+4
source share
4 answers
  • Use constructor injection for anything that needs context.
  • Use the DI structure of your choice and map the context.
  • Hide context as request area.
+4
source

If you are running IIS 7 with a built-in pipeline (the default), your ASP.NET module will see every request, even requests for static content (see http://learn.iis.net/page.aspx/508/wildcard- script-mapping-and-iis-7-integrated-pipeline / ),

If you still want to use the HTTP module to manage session / content for each request, I would consider using Lazy to avoid creating a context instance when it is not needed.

If you use an action filter, you need to finish all the work earlier if you place the context during OnActionExecuted. Wait and delete during OnResultExecuted if you want to delay the execution of the query until the view is displayed or use lazy / lazy loading of objects.

As Craig noted, IoC containers can also manage lifetimes for you.

+2
source

When I use the dependency injection infrastructure, I usually have a separate assembly with a domain model in it. This assembly also contains interfaces for repositories. The storage implementation contains code that actually creates an instance of an EF object object.

If this is a really simple application, but you are not doing DI, you can always instantiate an EF ObjectContext inside the constructor of your controller. Take a look at the ASP.NET MVC application examples at http://www.asp.net/mvc for good basic getting started information. I think that all three sample applications that they use now use EF.

+1
source

Are you using IIS 6 with wildcard mapping? CSS and images should not run BeginRequest.

Another popular way to do this is to override the OnActionExecuted and OnActionExecuting methods inside the base controller.

protected override void OnActionExecuting(ActionExecutingContext filterContext) { _context = new SomeEntities(); base.OnActionExecuting(filterContext); } protected override void OnActionExecuted(ActionExecutedContext filterContext) { _context.Dispose(); base.OnActionExecuted(filterContext); } 
+1
source

All Articles