Programmatically register a sitecore event

I’ve found that sometimes it makes sense to register several event handlers in a single initialize pipeline request rather than set up an individual xml node for all of them.  Additionally you can start to get creative and implement something to dynamically bind to events.

A simple use case

Here is a simple use case that can be expanded upon for whatever you need. It includes capturing an assembly and namespaced class and binding it to the item:saved event, enjoy!


public void AddEventProcessor()
	string typeStr = "[namespace].[class], [assembly name]";
	string[] parts = typeStr.Split(',');
	var assembly = Assembly.Load(parts[1].Trim());
	var type = assembly.GetType(parts[0]);
	var method = type.GetMethod("[event method name]");
	var o = Activator.CreateInstance(type);
	if (o != null)
		EventHandler e = (sender, args) =>
			method.Invoke(o, new[] { sender, args });
		Event.Subscribe("item:saved", e);