A common requirement when working with Episerver is to add custom functionality into the page's events, for example, you may need to run custom code when you save, delete or move content. One example that springs to mind, is re-indexing your website's search index. Luckily for us, Episerver provides a very easy provider called the Content Event provider to allow us to perform these sorts of tasks.

Content Events

In order to hook into Episerver CMS events, you will need to create an initialization module. If you have never come across one of these before, then I would recommend that you read this article first. We access the Content Events Provider in two ways, within an initialization module, via the context, like so:

Or via dependency injection, and a service locator, like so:

After you have access to the content events provider, you will have access to override a number of very useful events that get triggered within the CMS, like the PublishedContent, DeletingContent, MovedContent and SavingContent events to name a few. You can see a full list of all the events you can hook into here. The code we need to do this:

Commerce NOTE: You can also hook into Episerver commerce events the same way, as long as you add the:

Within the ModuleDependency attribute. The code above is pretty simple, we create an initialization module, call ServiceLocator with IContentEvents and then register the events you are interested in.

Once you have your events registered the methods will be hit when a content editor tries to perform one of the matching options. One standard thing you will very likely need to do is get access to the Episerver page or block that is attempting to be modified. There are several ways of doing this:

This will give you access to the object's IContent properties. If you want the whole object you can simply type it yourself like this:

Conclusion

In today's guide, we've talked about how you can hook into the Episerver CMS event pipeline. If you create an InitializationModule and use IContentEvents you can get access to a number of very useful events, like hooking into the Saving, Updating and Deleting event handlers. When you get into your code you will very likely want to get access to the object being manipulated. You can use the ContentEventArgs to get access to it.