Thursday, June 17, 2010

SP2010 Dispose Patterns and Broken WebParts

Today I was building a web part for SharePoint 2010 and ran across an interesting problem. The web part was working fine for authenticated users, but was failing for anonymous users. My first thought was that Lockdown might have been the problem, but it turned out after looking through SharePoint log files that I was running into a dispose problem:

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!

1 comment:

  1. hi Mike,

    i 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

    ReplyDelete