开发者

ObjectContext and Caching Per Request - Getting ObjectDisposedException

开发者 https://www.devze.com 2023-04-10 10:30 出处:网络
I\'m using an ObjectContext and storing it in HttpContext.Current.Items collection.I share the ObjectContext for a single request, but the framework also enables the ability to load a fresh, non-cache

I'm using an ObjectContext and storing it in HttpContext.Current.Items collection. I share the ObjectContext for a single request, but the framework also enables the ability to load a fresh, non-cached, distinct copy of the ObjectContext by turning on a flag. This way, for certain scenarios I can bypass HTTPContext altogether. There are valid reasons for this; one is I have various static references that use the ObjectContext, so each of these statics gets their own copy. Other scenarios are that a particular process may run in isolated fashion, therefore, it needs to be unique.

I'm trying to dispose of the shared ObjectContext's in Page Unload, and this works OK occasionally, but every now and then, I've been getting ObjectDisposedExceptions across requests (because some process tries to read data and invokes it). What I mean is that I'd get this exception this one time, invoke a postback, and get the error on that request too, and on the next requests as well. Closing and reopening the browser worked, but then I would get the error occasionally thereafter. It's random; one time the page works, later it doesn't. It's the same page, so it's not a bug with the logic.

This leads me to believe that:

  • The HttpContext.Current.Items collection is NOT isolated to one HttpRequest per user, OR:
  • The statics are somehow affecting the process and disposing of the shared 开发者_运维问答connection OR:
  • There is a bug I need to keep researching....

Has anyone experienced an issue with the first 2 items? Is my understanding wrong?


Neither of the first 2 items should happen. HttpContext is definitely used per single HTTP request processing and if statics not accessing HttpContext they should not affect your context.

There is other reason for this random behavior. Make sure that you don't share proxied / attached entities among requests (through session or cache) or use them after context from static were disposed.

By default all POCO entities are proxied and they keep reference to context internally. The reference to context is needed for dynamic change tracking and lazy loading. So if you don't manually detach entity prior to disposing context it will keep reference to disposed one and the first data modification or access to not loaded navigation property on the cached entity will throw this exception. EntityObject based entities do this as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号