Tuesday, February 15, 2011

Disposing SPSite and SPWeb

Most of the time when we are working with a site or a web we would put a using statement such as these:
using (SPSite siteCollection = new SPSite("http://evan.local"))
{
    // Code here
}
using (web = site.OpenWeb("search"))
{
    // Code here
}
The reason is so that site collection / the web are disposed properly.

However trying to do similar thing in:
using (SPSite site = SPContext.Current.Site)
{
       Code here
}
using (SPWeb web = site.RootWeb)
{
       Code here
}

Will give you the following error in the log:

Unexpected    Detected use of SPRequest for previously closed SPWeb object.  Please close SPWeb objects when you are done with all objects obtained from them, but not before.


The reason is the SPContext (together with the site collection/web property in the object) will be automatically disposed when SharePoint finish with it. By putting them into the “using” statement, we are actually disposing the object when they are still being used.

So the conclusion:
If you are opening a site / a web then use “using” statement;
If you are utilising a site/web object from a property of the SPContext object then please do not use “using” statement.

Have a great day everyone J

No comments:

Post a Comment