Expand Minimize

SPC110211: Dispose SPSite created by SPSiteCollection.Add

The SPSiteCollection.Add method creates and returns a new SPSite object. You should dispose of any SPSite object returned from the SPSiteCollection.Add method.

CheckId SPC110211
TypeName DisposeSPSiteCreatedBySPSiteCollectionAdd
Severity CriticalWarning
Type Assembly

The SPSiteCollection.Add method creates and returns a new SPSite object. You should dispose of any SPSite object returned from the SPSiteCollection.Add method. See sample from MSDN:
Bad Practice

void SPSiteCollectionAddLeak()
{
    SPWebApplication webApp = new SPSite("http://moss").WebApplication;
    SPSiteCollection siteCollections = webApp.Sites;
    SPSite siteCollection = siteCollections.Add("sites/myNewSiteCollection", "DOMAIN\User", "[email protected]");
    // SPSite siteCollection leak.
}

Good Practice
void SPSiteCollectionAddNoLeak()
{
    SPWebApplication webApp = new SPSite("http://moss").WebApplication;
    SPSiteCollection siteCollections = webApp.Sites;
    using (SPSite siteCollection = siteCollections.Add("sites/myNewSiteCollection", "DOMAIN\User", "[email protected]"))
    {
    } // SPSite object siteCollection.Dispose() automatically called.
}

Rule relates to SPDisposeCheckId 'SPDisposeCheckID_240'. To ignore this rule add the attribute '[SPDisposeCheckIgnore(SPDisposeCheckID.SPDisposeCheckID_240, "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", "SPC110211:DisposeSPSiteCreatedBySPSiteCollectionAdd", 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 AB. 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.