Subscribing to Sitecore Events in a PreApplicationStartMethod
Posted
Thursday, December 11, 2014 9:06 PM
by
Kevin
PreApplicationStartMethod is a neat .NET 4.0 trick that I only recently discovered. It allows you to have code in your assembly run during application startup. As Sitecore / ASP.NET developers, we can think of this like adding code to Application_Start in global.asax, only it’s in your assembly (no global.asax modifications needed). One thing this is commonly used for is to perform dependency injection, for example.
On the same day that I discovered PreApplicationStartMethod, I also found out that Sitecore events can be subscribed to at runtime rather than having to configure them via a .config file. When you combine these two techniques, you get a way to ensure that event handlers in your assemblies get wired up without requiring anything more than dropping your DLL in the bin folder.
Here’s a more concrete example… Let’s say I wanted to distribute a DLL that performs some action whenever an item is saved - maybe update a cache or write to an audit log or something. Your class might look something like this:
namespace [Namespace]
{
public class [Class]
{
public void OnItemSaved(object sender, EventArgs args)
{
// Extract the item.
var item = Sitecore.Events.Event.ExtractParameter(args, 0) as Item;
// Do something with the item...
// cache.Update(item);
// Log.Audit(“Item updated: “ + item.ID);
}
}
}
Then, you ordinarily would throw something like this into a .config file in App_Config\Include:
<events>
<event name=”item:saved”>
<handler type=”[Namespace].[Class], [Assembly]” method=”OnItemSaved” />
</event>
</events>
But with the addition of a PreApplicationStartMethod, you can avoid the .config file altogether. In order to activate your event handler, you’d just throw it in the bin folder of your Sitecore site. How is this done? First, throw an application level attribute into your class’ source file:
[assembly: PreApplicationStartMethod(typeof([Namespace].[Class]), "OnStart")]
Then, add the “OnStart” method to your class:
public static void OnStart()
{
var handler = new [Class]();
Sitecore.Events.Event.Subscribe(“item:saved”, new EventHandler(handler.OnItemSaved);
}
And that’s it! Now if you compile and drop your DLL into the bin folder, your event handler will run each time an item is saved, and no further configuration is needed!
The PreApplicationStartMethod was introduced in .NET 4.0 and apparently had some limitations (only one of them could exist per assembly was the big one), but as far as I know those limitations have been entirely removed with .NET 4.5. If you’re using Sitecore 7+, you’re already on .NET 4.5, so… Run with it! If you have some other creative uses for either that, or runtime subscription to Sitecore events - let me know about it.