Tutorial: Subscribe to events using PreApplicationStartMethodAttribute class
Sitefinity CMS enables you to subscribe for events using the Application_Start method of the Global.asax file. If you have custom code in the Global.asax file and you do not want to edit the file, you can subscribe to events using the PreApplicationStartMethodAttribute class of the .NET framework. The class provides expanded support for application startup.
First, you need to create a class that holds the subscription logic - the Subscriber class, for example. Next, you add the PreApplicationStartMethodAttribute class in the AssemblyInfo.cs file. Finally, from the AssemblyInfo.cs file, using the PreApplicationStartMethodAttribute class, you can initialize the Start()method of the Subscriber class. The AssemblyInfo.cs file references an assembly to be linked to during compilation of a dynamic resource.
Create the Subscriber class
The Subscriber class holds the subscription logic for a particular event, for example a Comment event (ICommentEvent).
- In Visual Studio, open your Sitefinity CMS project.
- In the context menu of the project, click Add » Class...
- Name the class Subscriber.cs, for example.
- Paste the following code:
In the sample code above, upon application startup, the static method Start() will be called. You use the Bootstrapper class and add an event handler to the initialized event. In this case, this is the ICommentEvent. In the Bootstrapper_Initialized method, check if the command name of the event arguments correspond to the relevant "Bootstrapped" value. Finally, using the Sitefinity CMS EventHub, subscribe for the ICommentEvent and pass the comment event handler that will be fired.
Add the PreApplicationStartMethodAttribute class
To initialize the Start() method of the Subscriber class:
- In Visual Studio, open your Sitefinity CMS project.
- Expand the Properties folder and open the AssemblyInfo.cs file.
- Add the following line:
[assembly: System.Web.PreApplicationStartMethodAttribute(typeof(SitefinityWebApp.Subscriber), "Start")]
- Build the solution.
As a result, the Start() method of the Subscriber class is initialized upon application startup.