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. Big Smile

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] because 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.

Leave a Reply