SharePoint Best Practices : COM Objects Disposal

While writing the code with SharePoint Server Side Object Model I often stuck with a question “What all objects should I be responsible to get disposed off?”

Though this seems to be a simple question but I found it worth researching upon to extract the list of all the Objects for which a developer is responsible to get disposed off in order to avoid any memory leaks in the farm.

In order to simplified the story I have divided SharePoint Objects following three categories:

List of Objects that must be Disposed explicitly

  1. SPWeb Object created with SPSite.OpenWeb
  2. SPSite objects created with SPSite.SelfServiceCreateSite
  3. SPWeb created by SPLimitedWebPartManager
  4. SPSite created by SPSiteCollection.Add
  5. SPSite created by SPSiteCollection[] index operator
  6. SPWeb created by SPWebCollection.Add
  7. SPWeb created by SPWebCollection[] index operator
  8. SPSite created with UserProfiles.PersonalSite

List of Objects that must be Closed (Not Disposed) explicitly:

  1.  PublishingWeb created by PublishingWeb.GetPublishingWebs[] index operator
  2.  PublishingWeb created by PublishingWeb.GetVariation
  3.  PublishingWeb created by PublishingWebCollection.Add

List of Objects that must Never be Disposed explicitly

  1. SPListEventProperties.Web
  2. SPWebEventProperties.Web
  3. SPItemEventProperties.Web
  4. SPItemEventProperties.ListItem.Web
  5. SPItemEventProperties.Web.Site
  6. SPItemEventProperties.ListItem.Web.Site
  7. SPFeatureReceiverProperties.Feature.Parent
  8. SPSite.RootWeb
  9. SPWeb.ParentWeb
  10. SPList.ParentWeb
  11. SPSite returned by SPControl.GetContextSite
  12. SPWeb returned by SPControl.GetContextWeb
  13. SPSite returned by SPContext.Current.Site
  14. SPWeb returned by SPContext.Current.Web

How to ensure proper disposal of object after the job is done:

There are following two Constructs available that can ensure the disposal of SharePoint Objects even if any unforeseen runtime exception occur in the code.

1. Use “Using Block”

using(SPWeb oWeb = osite.RootWeb)
}//oWeb will get disposed automatically as soon as using block ends

2. Use “Try, Catch & Finally Block”

SPWeb oWeb = osite.RootWeb;
catch(Exception ex)
oWeb.Dispose();  //oWeb will get disposed as soon as Dispose() method called.


Hope this will help someone in need…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s