Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to use the Session-per-request pattern, as is done frequently when using NHibernate in an ASP.NET environment.

My first thought was to put the code to create the context in the BeginRequest event handler in Global.asax, but I discovered that this event is firing not only for the initial request that actually does the work, but also for the subsequent requests for static files such as CSS and images.

I don't want to create a whole bunch of extra contexts when they're not needed, so is there a way I can just get my code to run on the initial request, and not the ones for the static files?

like image 763
Brian Sullivan Avatar asked Feb 26 '23 23:02

Brian Sullivan


2 Answers

  1. Use constructor injection for anything which needs a context.
  2. Use the DI framework of your choice and map the context.
  3. Scope the context as request-scoped.
like image 97
Craig Stuntz Avatar answered May 12 '23 08:05

Craig Stuntz


If you are running in IIS 7 with an integrated pipeline (the default), your ASP.NET module will see every request, even the 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 an HTTP module to manage a session/content per request, I'd consider using Lazy to avoid instantiating the context when it is not needed.

If you use an action filter, you'll need to finish all the work early if you dispose the context during OnActionExecuted. Wait and dispose during OnResultExecuted if you want to defer query execution until the view renders, or use deferred / lazy loading of entities.

As Craig pointed out, the IoC containers can also manage the lifetime for you.

like image 22
OdeToCode Avatar answered May 12 '23 08:05

OdeToCode