Best Practices: Closing and Disposable of MOSS Objects

Several blogs out there talk about the need to close and/or dispose of the SPSite and SPWeb objects. I took this to heart but then I started receiving the occasional error stating:

“Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”

The purpose of this blog entry is to clear this up (at least for me). The following link is to Microsoft’s documentation on this matter: http://msdn2.microsoft.com/en-us/library/aa973248.aspx

In summary:

  • If you create SPSite object using the “new SPSite()” constructors (any constructor override), then you need to call the “SPSite.Dispose()” method.
  • If you create the SPSite object using SPControl.GetContextSite(), then you should NOT dispose of the object.

This is Microsoft’s explanation as to why you should not dispose of the object when instantiated through using SPControl.GetContextSite():

“Because the SPWeb and SPSite objects keep an internal list that is derived in this way, disposing of the object may cause the SharePoint object model to behave unpredictably. Internally, Windows SharePoint Services enumerates over this list after page completion to dispose of the objects properly.”