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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With