Disposing of SPSite and SPWeb objects

Feb 27, 2009 at 4:13 PM
One change I would recommend to the code is disposing of the SPWeb and SPSite objects. Good documentation on the issue can be found here at MSDN Best Practices: Using Disposable Windows SharePoint Services Objects
Coordinator
Mar 5, 2009 at 12:25 PM
Edited Mar 5, 2009 at 12:27 PM
Quite the opposite, disposing the objects would crash your SharePoint pages. All SPWeb and SPSite objects are retrieved through the SPContext. As per the article you posted:

"SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web."

So no, none of the SPWeb or SPSite objects in SPCurrentUsers should be disposed.

 

Mar 5, 2009 at 3:50 PM
My bad, that's what I get for looking through the code too quickly :)
Coordinator
Mar 5, 2009 at 3:54 PM
At least now we have a topic discussion to clarify this particular issue, and future readers need not worry :-)
Mar 11, 2009 at 3:41 AM
A very good point!
Aug 19, 2011 at 7:27 AM

To do basic tasks, you can use the web exposed by the SPContext.Current.Web.   However, for some operations, you may want to launch your own copy of an SPWeb that can be closed, especially when doing a RunWithElevatedPrivileges command, since the privileges granted to a web are based off the context in which it was created:

using (SPSite site = new SPSite(HttpContext.Current.Web.Url))

 {

      using (SPWeb web = site.OpenWeb())

          {

            //Do stuff with API here

         }

}