Skip to content

Don’t Return an SPWeb after you’ve disposed the SPSite

For those of you playing the home game of “Should I dispose in SharePoint” may have noticed comments about edge cases like SPContext.Current.Site.RootWeb saying that the SPSite object automatically tracks the SPWeb objects that it creates and disposes them when it is disposed. I recently ran across some code that disposed of a SPSite object that they created and then returned the SPWeb object they created from the site to the caller. Here’s the problem with that…

The SPWeb object will already have been disposed by SPSite when it got disposed. Because of this fact that specific SPWeb that was created should never be used after calling .Dispose() on the SPSite. (You’re not supposed to use an object after having called it’s .Dispose() method.) Although the code *may* be working, it’s definitely not recommended because the object may throw an ObjectDisposed exception, it may transparently reconnect itself (meaning that it effectively ignored the dispose and starts camping out in memory), or may just start doing weird stuff.

Help Your SharePoint User

[Edited: 2009-02-13 – Minor clarification to exactly what I meant about SPWeb being used after SPSite per comment.]

So … never dispose your SPSite until you’re sure you’re done using all of the SPWebs you’ve created from it.

1 Comment

  1. Because of that SPWeb should never be used.

    This through me off. I think you meant to never use them after their spsite instance is disposed.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this: