EPiWiki.se  - EPiServer notes shared with others
 

Initialize static events

[Edit]
A common memory leak situation is when a dynamic object implements listeners of static events (sense Datafactory.Instance is only created once it should be concerned as a static class).

Warning


The application_start event in Global.asax is run when the web site are soft reset (when the web.config are changed or files are added or removed from the application and so on…). And attaching an static event in this method result in a memory leek.
In EPiServer version 6 and above use the initialization functionality.

Create an event register method In EPiServer pre version 6


With a singleton pattern



public class EventLoader
{
   private EventLoader(){}
   private static EventLoader _instance;
   private static Object _instanceLockObject = new Object();
   public static EventLoader CreateInstance()
   {
      if (_instance == null)
      {
         lock (_instanceLockObject)
         {
            _instance = new EventLoader();
         }
      }

      return _instance;
   }

   public void Initialize()
   {
      DataFactory.Instance.PublishedPage +=
         new PageEventHandler(Instance_PublishedPage);
   }

   static void Instance_PublishedPage(object sender, PageEventArgs e)
   {
      //Do stuff
   }
}

public class Global : EPiServer.Global
{
   public override void Init()
   {
       base.Init();

       EventLoader.CreateInstance().Initialize();



With a EPiServer plugin functionality



public class MyEventLoader : EPiServer.PlugIn.PlugInAttribute
{
    public static void Start()
    {
        //Attach to the right events
        DataFactory.Instance.PublishedPage +=
           new PageEventHandler(Instance_PublishedPage);
    }

    static void Instance_PublishedPage(object sender, PageEventArgs e)
    {
        //Do stuff
    }
}

Version author:
Mattias Lövström

EPiServer version

All