In this tutorial, you will learn how to hook into the Umbraco events pipeline. Umbraco V8 ships with a number of handy hooks. These hooks allow for custom code to be triggered after certain actions have occurred. By simply registering some custom code against an event you can change the default CMS behaviour. For example, when a content editor tries to save a page, you can force some validation to be run. If the validation fails, you can prevent Umbraco from saving the page. Clever!
When it comes to hooking into events there are loads of things that you can hook into, these include:
MemberServiceevents - documentation here
ContentServiceevents - documentation here
MediaServiceevents - documentation here
ContentTypeServiceevents - documentation here
DataTypeServiceevents - documentation here
FileServiceevents - documentation here
- 'LocalizationService' events - documentation here
Each type of event handler exposes its own set of custom events. For example, the content service allows you to hook into events such as page, - Moved moving a page, publishing a page, saving a page, copying a page, etc... There are far too many events to cover in a single post, so I suggest you read the documentation to find out more.
The good news is that hooking into an event is simple. Simply create a composer and a container, register an event handler with the appropriate service and off you go. Let see how to do that now.
Event Handler Composer and Component
To hook into one of these events you will need to create a component and a composer. If you are new to composers and you are struggling to grasp why you need one, then you can find more about them here Umbraco V8 Components And Composers Explained. The code to hook into the event pipeline is fairly simple as shown below:
As you can see on Line 5, we hook into an event using
MemberService. Using the
+= operator, we can define a method that will automatically subscribe to an event. When the CMS triggered that event and the composer is registered, the method you implement will be called. This code uses the
MemberService. To hook into the content service is exactly the same:
Within the subscribed method you are free to add any custom code you desire. It really is that simple! On its own, this class will do nothing. The class is registered using
IComponent meaning it is a Umbraco user component. A component on its own will do nothing. A component will need to be registered within Umbraco using a composer. The code to create the corresponding composer is shown below:
Now the component is registered within Umbraco the event handler will auto-subscribe to the corresponding CMS events when they happen and your custom code will be run. You will now have the ability to hook into the content publishing events. Happy coding 🤘