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

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *