Disposing ObjectContext (per-request) after use
I am using creating one ObjectContext per-request concept. Technically, I am adding ObjectContext instance to HttpContext.Current.Items. But I do not know how to kill this instance properly. Is it safe to use HttpModule and disposing ObjectContext within? I mean, HttpModule might be called for any kind of request. I do not want to use DI/IoC matters, because the project need to lightweight (no third party libs allowed).
UPDATE: here the simple code: Created a per-request ObjectContext (Entities class)
public static class ObjectContextPerRequest
{
public const string ObjectKey = "_per_request_context_key";
public static Entities PerRequest
{
get
{
if (HttpContext.Current.Items[ObjectKey] != null)
{
var eContext = new Entities();
HttpContext.Current.Items.Add(ObjectKey, eContext);
return eContext;
}
return HttpContext.Current.Items[ObjectKey] as Entities;
}
}
}
and a disposer module:
class ObjectContextManagerModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.EndRequest += (s, e) => { Dispose(); };
}
public void Dispose()
{
if (HttpContext.Current.Items[ObjectContextPerRequest.ObjectKey] != null)
{
var edmx = (ObjectContext)HttpContext.Current.Items[ObjectContextPerRequest.ObjectKey];
开发者_如何学编程 edmx.Dispose();
edmx = null;
}
}
}
It'll be safer to create the context during the BeginRequest and then dispose of it during either EndRequest or ReleaseRequestState (probably EndRequest). Init is when the module is fired up, Dispose is when the module itself is disposed, and modules don't get created and disposed on every request.
* UPDATE for comment *
The module should use its Init method to attach to application events, like so:
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(OnBeginRequest);
app.EndRequest += new EventHandler(OnEndRequest);
}
Note that there are other syntaxes available, but that's the one that's documented on MSDN.
This will fire on every request that hits your application. So if your IIS setup routes static file requests (e.g. images and css files) through the app (which is true for IIS 7 in integrated pipeline mode), then your event handlers need to account for that by not spinning up an ObjectContext instance in cases you don't need one.
* UPDATE for MVC *
Since you're using an MVC app, you could also consider doing this in a controller base class or in an actionfilter, using the OnActionExecuting and OnActionExecuted calls.
As an ActionFilter, you can ensure you apply it only to controllers that need the data context.
精彩评论