Thursday, January 21, 2010

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

Developing in SharePoint you can come across this error (Trying to use an SPWeb object that has been closed or disposed and is no longer valid) for so many reasons.
The one I faced today was because I was using a SPWeb object initialized to the current context, so something like:
SPWeb site = SPContext.Current.Web

In order to skip the Dispose statement I wrapped the my code into a using block, so I had something like:

using (SPWeb site = SPContext.Current.Web)
{
...
}

The problem is that when we execute SPWeb site = SPContext.Current.Web, an object is not actually created and the site variable only gets a reference to the existing object, which in this particular case is the current context. Then at the end of the using block, the code will actually dispose the current context, which is a non-desirable efect.

So in order to avoid this error, just don't try to dispose the current context!

You can read more info about all that in: Best Practices: Using Disposable Windows SharePoint Services Objects (http://msdn.microsoft.com/en-us/library/aa973248.aspx)

0 comments:

Post a Comment