On a lot of projects, you’ll need to hook into the Umbraco pipeline. In today's tutorial, I'll briefly explain why you may want to consider using an ApplicationEventHandler, what sort of things you can use it for and the code you'll need to write in order to create one.
What things will I put in my initialisation module?
If, like me, you want to write decoupled and testable code, you might want to use a dependency injection framework, like Ninject, or StructureMap. On a project, you'll need to define your dependency injection configurations, this could also be done from an ApplicationEventHandler. You can also use the global.ascx, but my preference leans towards trying to keep that file as lean as possible, but again it's up to your preferences. Asides, from dependency injection, you might want to run some code on start-up, like sending an email, doing maintenance checks etc.. run some code when a certain document type is published to name the most common scenarios. In Umbraco World, this is done by implementing an ApplicationEventHandler.
When you create a class that inherits from ApplicationEventHandler, it will be executed on 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 you might not care too much if a context is a set-up etc.. so I won't go into too much detail. Although it is useful to know you can override:
Within any of these overrides, you can then register events, including on application start, publishing, saving. You can also hook into, create an event handler and implement a method, like so:
You may be asking where you need to add your ApplicationEventHandler code? I used to put mine in the App_Start folder, but it caused a lot of 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.
ApplicationEventHandler Modules Takeaway
If you need some code to run when your website starts.. you will need to implement 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!