SPC056003: Do not instantiate SPSite in Receiver

Do not instantiate an SPSite object within an event receiver.

TypeName: DoNotInstantiateSPSiteInEventReceiver
CheckId: SPC056003
Severity: Warning
Type: AssemblyFileReference
Resolution

Do not instantiate an object of type 'Microsoft.SharePoint.SPSite'. Best practise is to get these objects from the current context.

Bad Practice:

public override void ItemDeleting(SPItemEventProperties properties)
{
  using (SPSite site = new SPSite(properties.WebUrl))
  {
    using (SPWeb web = site.OpenWeb())
    {
      SPList list = web.Lists[properties.ListId];
      SPListItem item = list.GetItemByUniqueId(properties.ListItemId);
      // Operate on an item.
    }
  }
}

Good Practice:
public override void ItemDeleting(SPItemEventProperties properties)
{
  // Retrieve SPWeb and SPListItem from SPItemEventProperties instead of
  // from a new instance of SPSite.
  SPWeb web = properties.OpenWeb();
  // Operate on the SPWeb object.
  SPListItem item = properties.ListItem;
  // Operate on an item.
}

Links

comments powered by Disqus