Thursday, April 16, 2015

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


A common mistake that people make in their code with this exception.
SPWeb, SPSite objects leak memory if they are not disposed properly.
The problem is so much talked about that as soon as we think of SPSite and SPWeb we unconsciously put using (SPWeb spweb = blah blah)
However when you use SPContext to get site or web object you should not be using “USING” or you should not dispose that object.  SPContext is passed to another web part on the page and SharePoint will dispose it when done.
Hence if you have been using (SPSite spsite = SPContext.Current.Site) it is wrong.  It might not always break as you might just have one web part in your code but you will see it break as soon as you add another web part and may be try to check in the page.

so change
using (SPSite spsite = SPContext.Current.Site)
to
SPSite site = SPContext.Current.Site.