tags:

views:

230

answers:

2

When writing web parts in SharePoint, are you implementing IDisposable via a using clause? Or, do you dispose of your objects in try/catch/finally? Both? Depends? Why'd you pick one over the other?

Background:

I'm working on a bit of inherited code that doesn't implement IDisposable, so I've been reading up to correct the problem. MSDN has a nice article covering the "best practice":

http://msdn.microsoft.com/en-us/library/aa973248.aspx

that recommends using, but then goes on to say that in many cases it's not advisable to be using using.

+5  A: 

I can understand the abiguity in the article - the real answer is as clear as mud :)

When it comes to web part development (or developing with the SharePoint API in general), disposing of certain objects (specifcally, SPOM objects) will yield unpredictable results if you don't instanciate your objects correctly.

In particular, if you get an object reference to the SPSite or SPWeb from the current context and try to dispose of it (either with a using clause or try/finally), you'll get object reference error from the SharePoint stack.

The right way to do dispose of your SP objects (SPSite, SPWeb, etc) is to instanciate a new SP object (as opposed to using the context to get it) from a site using a URL. For example:

using (SPSite siteCollection = new SPSite("http://your_site_url"))
{
  using (SPWeb site = siteCollection.OpenWeb("News"))
  {
    //do stuff with your news web
  }
}

Here is an example of code that will throw an object reference error if you attempt to use it:

using(contextSite = SPControl.GetContextSite(Context))
{
  using (SPWeb site = siteCollection.OpenWeb("News"))
  {
    //do stuff with your news web
  }
}

The error won't occur during the using block, but will occur later downstream when SharePoint tries to do something internally with the site.

In terms of general use, I'm a big fan of using() over try/finally if you've got an IDisposable object. The only time I opt for try/finally is if I need to do extra logic around de-allocating non-IDisposable objects.

Hope this helps!

Adam McKee
(+1) It's certainly less muddy now, thanks!
vinny
+1  A: 

Perhaps this link might help you also: http://blogs.msdn.com/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx

Flo
My original link is synched to yours (Roger is one of the MSDN authors). However, it did hip me to the http://code.msdn.microsoft.com/SPDisposeCheck tool that I completely missed from the MSDN article.
vinny