Share via


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 of?”

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

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

List of objects that must be disposed of 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 of) 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 of 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 an 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 occurs in the code.

1. Use “Using Block”

using(SPWeb oWeb = osite.RootWeb)
{
}//oWeb will get disposed automatically as soon as using block ends
  1. Use “Try, Catch & Finally Block”
try
{
SPWeb oWeb = osite.RootWeb;
}
catch(Exception ex)
{
throw;
}
finally
{
oWeb.Dispose();  //oWeb will get disposed as soon as Dispose() method called.
 
}

Hope this will help someone in need.