Trying to use an SPWeb object that has been closed or disposed and is no longer valid.
It's an interesting error message, considering that I was disposing of my object, but only after I'd finished with it. I believe the problem wasn't that my code was using a disposed SPWeb object, but rather that I had closed an SPWeb that SharePoint was relying upon.
Here was the original code, which, according to Best Practices, was closing objects that don't need to be closed:
using (SPSite site = SPContext.Current.Site) { using (SPWeb web = site.RootWeb) { SPList myList = web.Lists["myList"]; //code here to find a list item } }
And the fix was as simple as changing it to this:
SPSite site = SPContext.Current.Site; SPWeb web = site.RootWeb; SPList myList = web.Lists["myList"];
I'm not so sure this would have broken a SharePont 2007 site, but it's a good reminder to make sure you are following Best Practices for disposing objects!
hi Mike,
ReplyDeletei have a question..
doesn't fixing the code to that causes leakes??
and when should I dispose of SPSite and SPWeb objects?
thanks,
Ran Yair