views:

167

answers:

1

The reason I ask is because the HttpContext.Current.Items collection seems like it would be a good place to put IDisposable objects such as a DataContext so that a Repository might access it transparently without having to to inject any dependencies related to a specific ORM technology into the Repository. This would also allow the repository to decide whether to engage in a UnitOfWork or take on the additional responsibility of actually persisting any changes.

For example:

The Page:

protected void Page_Load(...)
{
   Items[KeyValueFromConfigurationFile] = new DataContext();
   var repo = new Repository();
   var rootEntity = repo.GetById(1);
}

The Repository:

public virtual TEntity GetById(int id)
{
   var ctx = HttpContext.Current.Items[KeyValueFromConfigurationFile] as DataContext;
   return ctx.TEntities.SingleOrDefault(p => p.Id == id);
}

Of course, I would check for nulls and perform the steps needed to get a DataContext if it wasn't available in the HttpContext.Current.Items collection.

So, back to my original question given the above code: Will the HttpContext.Current be disposed along with any of the objects contained in its Items collection even if an exception is thrown?

Thanks for all the help.

+1  A: 

The Items collection of the HttpContext will be around for the lifetime of the Request. After that it is disposed and all references exclusively tied to it will be disposed as well.

An Exception doesn't matter in this case, because the Request will still end.

Zyphrax
Exactly what I was hoping to hear. Thank you very much.
mkelley33