Using object context on application_endrequest

I ran into a problem with the context of an EF4 object, which I store inside HttpContext.Current.Items, and then want to delete as soon as the request is fully processed.

In the Aplication_EndRequest event, I call the Terminate () method on the RepositoryContext, which will find the active ObjectContext from the HttpContext.Current.Items collection and call Close () on its connection and Dispose () on it.

The problem is that sometimes I get strange behavior on one of my pages. In some cases, I get an error message:

The ObjectContext instance has been deleted and can no longer be used for operations that require a connection.

I thought that maybe this could happen, since not only page requests raise the Application_EndRequest event as soon as they end, but also image requests, etc. ", and perhaps other requests sometimes place the ObjectContext request on the home page before it finishes doing its job, but this should not happen, because everything is done in the HttpContext.Current.Items collection, which, of course, is not shared between HTTP requests.

In addition, from the study it may be caused due to lazy loading of some db requests, but it should not be here because I do not call Dispose elsewhere in the code (I checked) and therefore Dispose () on EndRequest should only be called after completing everything , right?

, ? ? ?

!

+5
2

, Dispose() ObjectContext. , , , - Dispose() Application_EndRequest. , .

, ObjectContext HttpContext. . , ObjectContext using, Dispose() .

+1

, , ObjectContext, , , - , :

using(var context = ContextProvider.GetCurrentContext()){
    ...
}

ObjectContext .

, ObjectContext, :

ObjectContext Dispose :

public override void Dispose() {
    throw new InvalidOpearationException("Gotcha!");
}

public void ActuallyDisposePlease() {
    base.Dispose();
}

Application_EndRequest ActuallyDisposePlease().

, //, .

+1

All Articles