Search code examples
sharepointsharepoint-2010dispose

Should I dispose SPWeb objects (in general)?


If you start SharePoint and learn about disposing SPSite and SPWeb, almost everybody suggests to use the "using"-construct if you work with new instances of SPSite and SPWeb.

using (SPSite s = new SPSite("http://yourserver")
{
    using (SPWeb web = s.OpenWeb("http://yourweb")
    {
         // do fancy stuff here
    }
}

I did that too. However, if you look into the SPSite.Dispose() method, you'll notice that SPSite keeps a reference of its SPWebs created by SPSite.OpenWeb(). On SPSite.Dispose(), all SPWebs tied to this SPSite are diposed. I think (but Im not sure) that virtually all methods which are creating a new SPWeb are adding this SPWeb to the internal collection 'm_openedWebs'.

This being said, I wonder why you would ever dispose a SPWeb object? Are there any real-world scenarios were you should dispose SPWeb objects?

UPDATE

I just realized, that I spared a little detail which might be important. The SPSite object does not call Dispose() on its child SPWebs, but it is calling Close(). In the current implementation of SharePoint, this is the same as Dispose(), becasue SPWeb.Dispose() just contains:

public void Dispose()
{
    this.Close();
}

So one reason for disposing SPWeb objects might be to be compatible to future SharePoint implementations where SPWeb.Dispose() does not only call SPWeb.Close(). I still find it akward to "double-dispose" my SPWebs only for that reason.


Solution

  • You're right, disposing the SPSite will close the associated SPWeb objects.

    The main scenario where you want to close SPWeb's right away is when you do something like:

    foreach (SPWeb web in site.AllWebs) 
    { 
         // do something with the web object 
        web.dispose();        // <-- this is mandatory!
    }
    

    For normal opening and closing of one SPSite/SPWeb this doesn't matter but I would argue it is still good practice (especially for new SharePoint developers).

    If you haven't already, I would highly recommend reading Stefan Goßner's post: http://blogs.technet.com/b/stefan_gossner/archive/2008/12/05/disposing-spweb-and-spsite-objects.aspx