Is an HttpContext.Current object even if an exception is thrown?

The reason I ask is because the collection HttpContext.Current.Itemsseems that it would be nice to place objects IDisposable, such DataContextthat the repository can access it transparently, without having to inject any related dependencies to a particular ORM technology into the repository. It will also allow the repository to decide whether to participate in UnitOfWorkor take on additional responsibility for actually saving any changes.

For example:

Page:

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

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 the zeros and follow the steps required to get DataContextif it was not available in the collection HttpContext.Current.Items.

, , : HttpContext.Current , , ?

+3
2

HttpContext.Current.Items . . global.asax Application_EndRequest:

            foreach (var item in HttpContext.Current.Items.Values)
            {
                var disposableItem = item as IDisposable;

                if (disposableItem != null)
                {
                    disposableItem.Dispose();
                }
            }
+13

, , , , , . " ; ", OnEndRequest for :

        foreach (var item in HttpContext.Current.Items.Values)
        {
            var disposableItem = item as IDisposable;

            if (disposableItem != null)
            {
                disposableItem.Dispose();
            }
        }

, , HttpContext, foreach . , :

        int size = HttpContext.Current.Items.Count;
        if (size > 0)
        {
            var keys = new object[size];
            HttpContext.Current.Items.Keys.CopyTo(keys, 0);

            for (int i = 0; i < size; i++)
            {
                var obj = HttpContext.Current.Items[keys[i]] as IDisposable;
                if (obj != null)
                    obj.Dispose();
            }
        }
+2

Source: https://habr.com/ru/post/1712938/


All Articles