Closing of the SPWeb or SPSite Object within Web Part Development
I wrote a base class for one of my clients and started to gather some web part information within my base class inheritted from my Web Part. I started to use the base class and it worked well, until I wanted to edit the web part and tried to change some of the properties attached to the web part. As soon as I applied the changes I would get an error of, "The SPWeb object is no longer valid". Looking through my code I realised I was explicitly closing the spweb object in a final statement. Code looked like this;
SPWeb oSite = SPControl.GetContextWeb(Context);
try
{
return oSite.ID.ToString();
}
catch (Exception exm)
{
throw new Exception(exm.Message);
}
finally
{
oSite.Dispose();
}
I removed the oSite.Disposed from my finally section and it all worked. 
What I realised was that when you are using the Current Context to create a spweb object, you should not close or dispose of the object, or use it within a using statement, [using statement automatically call's the dispose method at the end of the using section] becuase other places within your site page, will more then likely want to use this object. E.G when you want to change a property of a web part, etc...
There is a great article on MSDN that provides developers with best practices of disposing sharepoint services object.
Posted on SharePoint Blogs
Del.icio.us |
Digg It |
Technorati |
Blinklist |
Furl |
reddit |
DotNetKicks
Read the complete post at http://www.sharepointblogs.com/bobbyhabib/archive/2007/11/28/closing-of-the-spweb-or-spsite-object-within-web-part-development.aspx