Expand Minimize

Dispose SPSite created by SPSiteCollection[] index operator

The SPSiteCollection [] index operator returns a new SPSite object for each access. An SPSite instance is created even if that object was already accessed.

CheckId SPC110212
TypeName DisposeSPSiteCreatedBySPSiteCollectionIndex
Severity CriticalWarning
Type Assembly

The SPSiteCollection [] index operator returns a new SPSite object for each access. An SPSite instance is created even if that object was already accessed. The following code samples demonstrate improper disposal of the SPSite object. See sample (source: MSDN):
Bad Practice

void SPSiteCollectionIndexerLeak()
{
  using (SPSite siteCollectionOuter = new SPSite("http://moss"))
  {
    SPWebApplication webApp = siteCollectionOuter.WebApplication;
    SPSiteCollection siteCollections = webApp.Sites;
    
    SPSite siteCollectionInner = siteCollections[0];
    // SPSite siteCollectionInner leak.
  } // SPSite object siteCollectionOuter.Dispose() automatically called.
}

Good Practice
void SPSiteCollectionIndexerNoLeak()
{
  using (SPSite siteCollectionOuter = new SPSite("http://moss"))
  {
    SPSite siteCollectionInner = null;
    try
    {
      SPWebApplication webApp = siteCollectionOuter.WebApplication;
      SPSiteCollection siteCollections = webApp.Sites;
      
      siteCollectionInner = siteCollections[0];
    }
    finally
    {
      if (siteCollectionInner != null)
        siteCollectionInner.Dispose();
    }
  } // SPSite object siteCollectionOuter.Dispose() automatically called.
}

Rule relates to SPDisposeCheckId 'SPDisposeCheckID_230'. To ignore this rule add the attribute '[SPDisposeCheckIgnore(SPDisposeCheckID.SPDisposeCheckID_230, "Caller will dispose")]' to your method.

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("SPCAF.Rules.MemoryDisposalGroup", "SPC110212:DisposeSPSiteCreatedBySPSiteCollectionIndex", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.