In Sharepoint development we often need to attach/detach event receivers to specific list (by specific list I mean single list on the web site where feature is activated, not to all lists created with particular list template). So I decided to make this post for future references also for myself. As title says it will show how to attach event receivers to particular event type (e.g. ItemAdded or ItemUpdated) safely, i.e. if feature will be activated several time with force flag, the same event receiver won’t be attached again and as result it won’t be triggered several times which may cause problems on your environment.
We will need feature with feature receiver: attaching of list event receiver will be made in FeatureActivated() method and detaching in FeatureDeactivating():
Like shown in example above before to add or remove event receiver for specified event type it checks first that event receiver is attached to the list or not. I.e. it will be safe to activate this feature multiple times with force parameter on the same web site and then deactivate it. Also using this technique it will be possible to safely attach event receivers to another event types after feature was already activated: it won’t attach the same receiver to existing events and will only attach it for new ones.