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
{
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
{
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.
[SuppressMessage("SPCAF.Rules.MemoryDisposalGroup", "SPC110212:DisposeSPSiteCreatedBySPSiteCollectionIndex", Justification = "Provide reason for suppression here")]