Loading...
Area: Optimizely CMS
ARCHIVED This content is retired and no longer maintained. See the latest version here.

Recommended reading 

This topic describes how to create an initialization module to work with the initialization system in the EPiServer platform.

How it works

When you create your own initialization module, add a reference to EPiServer.Framework.dll. The following Initialization code example shows how a property is set up with a default implementation in Initialize and then the process is undone in Uninitialize:

C#
[InitializableModule]
public class SampleInitialization : IInitializableModule
{
    public void Initialize(InitializationEngine context)
    {
    }
    public void Uninitialize(InitializationEngine context)
    {
    }
}

Recommendations

  1. Allow for Initialize to be called multiple times. If you carry out multi-step initialization in your Initialize method and if it is re-executed because of an error – ensure that the application handles this scenario correctly. Example:
    C#
    private bool _eventAttached;
        public void Initialize(InitializationEngine context)
        {
              if (!_eventAttached)
           {
                 SomeClass.AnEvent += MyEventHandler;
                  _eventAttached = true;
           }
                    MethodThatMayThrowException();
        }
    This Initialize method may generate an error after the event handler is hooked up. The initialization system invokes the Initialize method again on the next request that reaches the web application and if the event hook-up is not protected with a flag, it gets added again.
  2. The initialization engine makes sure that your code executes in a single-threaded manner. You do not need to lock regions when you deal with shared state. This guarantee is only made for Initialize and Unintialize when you execute through the initialization system. If you have custom code that makes calls directly into your initialization module, then you may need to deal with multi-threading issues.
  3. Remember that the initialization system tracks the initialization state of your module.
  4. Do an implementation of Uninitialize. Anything you do with Initialize you should undo with Uninitialize in the reverse order of Initialize.
  5. If you are using the CMS API make sure you are adding a module dependency to CMS using [ModuleDependency(typeof(EPiServer.Web.InitializationModule))].

Related topic

Do you find this information helpful? Please log in to provide feedback.

Last updated: Sep 21, 2015

Recommended reading