Best Practices with Event Receivers

Applies to: SharePoint Foundation 2010

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

Using Objects in 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.
        }
    }
}
 Public Overrides Sub ItemDeleting(ByVal properties As SPItemEventProperties)
    Using site As New SPSite(properties.WebUrl)

        Using web As SPWeb = site.OpenWeb()
            Dim list As SPList = web.Lists(properties.ListId)
            Dim item As SPListItem = list.GetItemByUniqueId(properties.ListItemId)
            ' Operate on an item.
        End Using
    End Using
End Sub

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.
' Retrieve SPWeb and SPListItem from SPItemEventProperties instead of
' from a new instance of SPSite.
Dim web As SPWeb = properties.OpenWeb()
' Operate on the SPWeb object.
Dim item As SPListItem = 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).