In this tutorial, you will learn how to hook into the Umbraco pipeline in code. This magic is achieved using a class called the ApplicationEventHandler
. There are many reasons why you might want to hook into the Umrabco event pipeline. For me, the biggest reason for any project is to enabled dependency injection (DI). Dependency injection is a must on all MVC projects in my opinion. Umbraco V7 does not come with DI out-of-the-box. It will be up to you to implement it. This means you will need to use a dependency injection framework, like Ninject, or StructureMap. How do we do this... by hooking into a pipeline 🎉🥂
It is also possible to register dependency injection in the sites global.asax
. My preference is to keep that file as lean as possible, however, this is definitely a personal preference. Dependency injection is definitely not the only reason why you might want to hook into the Umbraco pipeline. You might want to run some code on start-up, like sending an email, perform a site health check, warm up a cache. You may want to hook into the page pipeline and run some code when a certain document type is published In Umbraco, hooking into the pipeline is done by implementing a class that inherits from ApplicationEventHandler.
The skeleton code required to hook into the Umbraco pipeline is shown below:
When you create a class that inherits from ApplicationEventHandler
, it will be executed on the application start-up. In the ApplicationEventHandler
you can override three methods, depending on when you want your code to execute. In most cases, if you just want your code to run on start-up. When running code on start-up be aware that the site context might not be fully initialized when your code runs, this can lead to odd bugs otherwise!
Within any of these overrides, you can then register events, including on application start, on page publish, and on-page save. You can also create events to hook into Umbraco when a page is moved to the trash!
You may be asking where you need to add your ApplicationEventHandler
code in your solution? I used to put all of my event handlers within the App_Start
folder, however, this caused too many issues. If you forget to set the code to compile, you can end up having your handler running twice, which is annoying. Instead, I generally keep all code out of my web project and put it all in a separate class library. As long as the website references the code, on start-up, it will be magically called. Meaning, the location of the files isn't too important, place them in a folder that makes you happy!
If you need some code to run when your website starts.. you will need to implement a class that inherits from ApplicationEventHandler
. Creating an ApplicationEventHandler
is very simple and quick to get started with, all you need to do is to inherit from the correct base class, override the write method and off you go! Happy Coding 🤘