I have a question regarding the usage of using statements around ObjectContext objects in webforms.
If we have a form setup with two methods, say 'Load()' and 'Save()' and both require usage of the ObjectContext would it be better practice to create an instance variable of the context and use it in both methods, relying on the lifespan of the class to implicitely dispose of the object, or to explicitely create two instances of the object context, wrapped in a using, once per method?
The reason I ask is that I’m unsure of two things. A) whether the overhead of instantiating the object context is high enough to warrant leaving the context open for the entire class to use, or on the flip side B) whether the existence of the object context for the lifespan of the class is too long and we should be explicitely closing it after the unit of work is complete?
Any ideas/suggestions/best practices for this sort of environment?
You can manage the
ObjectContextper request, don’t think about it as per Page or WebForm, it has to be bound to the currentRequest, check here for more details:How to Manage ObjectContext Per Request in ASP.NET
this is more or less also what usually done for NHibernate’ sessions.
Personally I used to code with a using statement and create/dispose the ObjectContext immediately and in every method I needed it. In some cases you have to pay special attention in this way because your entities will be loaded from one context and saved in another one and I had to attach them back if I recall correct. It has been a while I did so…