Export (0) Print
Expand All

Best Practices with Event Receivers

SharePoint 2010

Last modified: January 13, 2010

Applies to: SharePoint Foundation 2010

This topic addresses common issues related to efficient use of event receivers.

Do not instantiate an SPWeb, SPSite, SPList, or SPListItem object within an event receiver. Event receivers that instantiate these objects instead of using the instances passed via the event properties can cause the following issues:

  • Significant additional roundtrips to the database (one write operation can result in up to five additional roundtrips in each event receiver).

  • Calls to the Update method on these instances can cause subsequent Update calls in other registered event receivers to fail.

Bad Coding Practice

Instantiating an SPSite object inside an event receiver

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 Coding Practice

Using SPItemEventProperties

// 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.

If you do not retrieve SPWeb, SPSite, SPList, or SPListItem objects from SPItemEventProperties and instead instantiate those objects within an event receiver, when you call Update on the new instances, you must clear it with the Invalidate method in the appropriate child class of SPEventPropertiesBase (for example, SPItemEventProperties.InvalidateListItem or SPItemEventProperties.InvalidateWeb).

Show:
© 2014 Microsoft