SPC110213: Dispose SPWeb created by SPWebCollection.Add

The SPSite.AllWebs.Add method and SPWebCollection.Add method creates and returns an SPWeb object. You should dispose of any SPWeb object returned.

TypeName: DisposeSPWebCreatedBySPWebCollectionAdd
CheckId: SPC110213
Severity: CriticalWarning
Type: AssemblyFileReference
Resolution

The SPSite.AllWebs.Add and SPWebCollection.Add method creates and returns an SPWeb object. You should dispose of any SPWeb object returned from SPSite.AllWebs.Add. See sample from MSDN:

Bad Coding Practice

void AllWebsAddLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    SPWeb web = siteCollection.AllWebs.Add("site-relative URL");
    // SPWeb object leaked.
  }  // SPSite object siteCollection.Dispose() automatically called.
}

Good Coding Practice
void AllWebsAddNoLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb web = siteCollection.AllWebs.Add("site-relative URL"))
    {
    } // SPWeb object web.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Remarks

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

Links

comments powered by Disqus