Is the HttpContext.Current disposed even if an exception is thrown?
c#, datacontext, idisposable, linq-to-sql, repository-pattern
Solution
Objects in HttpContext.Current.Items will not automatically be disposed. You would need to handle this yourself. You can do it in the global.asax Application_EndRequest:
foreach (var item in HttpContext.Current.Items.Values)
{
var disposableItem = item as IDisposable;
if (disposableItem != null)
{
disposableItem.Dispose();
}
}
Problem
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?