22 February 2009

EPiServer: Initialising plug-ins shipped in a separate DLL

Recently I have been doing a lot of work with trying to encapsulate EPiServer plugins into a single DLL to share between projects. The objective is to get a clean architecture going so that all you have to do is drop a DLL into a project’s BIN folder and everything registers cleanly without any configuration or code.

One issue has been how to ensure that code is executed when the website application initialises. In my case I wanted to set up a delegate that fires whenever a page is about to publish. Normally, you’d do this by adding code into GLOBAL.ASAX file that sets up a delegate for the DataFactory.PublishingPage event, although this isn’t practical when you’re looking to encapsulate everything inside a portable DLL.

The solution is to create a Page plug-in and take advantage of the static Initialize method that is called when EPiServer first starts up. The code below shows how to set up a class that hooks up a delegate to the PublishingPage event so that you can fire some code every time a page publishes.

using System;
using EPiServer;
using EPiServer.Core;
using EPiServer.PlugIn;
namespace BenMorris.EPiServer
{
    [PagePlugIn(DisplayName = "Startup plugin",
                Description = "Executes initialisation code when EPiServer starts.")]
    public class StartupPlugin
    {
        ///<summary>        
        /// Fires when EPiServer initialises.        
        ///</summary>        
        public static void Initialize(int bitflags)
        {
            //* Add in the delegate for PublishingPage event            
            DataFactory.Instance.PublishingPage += newPageEventHandler(Instance_PublishingPage);
        }         

        ///<summary>        
        /// Fires when a page is about to be published.        
        ///</summary>        
        ///
        public static void Instance_PublishingPage(object sender, PageEventArgs e)
        {
            //* Do something here - the page data is available via e.Page        
        }
    }
}

Filed under ASP.NET, CMS.