Monday, 15 March 2010

HttpModule and Application_Start

Unfortunately there is no “Start” event to hook onto for HttpModules.  Instead you should use Init() – be aware though that there may be multiple instances of your http module, serving many threads in the appdomain.  So you need a bit of thread sync’ing in order to ensure that your start-up code only executes once.

    public class MyHttpModule : IHttpModule
    {
        /// <summary>
        /// Mutex object which gives the lock statement something to get an exclusive lock on
        /// </summary>
        private readonly static object _mutex = new object();
        /// <summary>
        /// Flags whether the application has started
        /// </summary>
        private static bool _isInitialised = false;
        #region IHttpModule Members
        public void Dispose()
        {
        }
        public void Init(HttpApplication context)
        {
            if (!_isInitialised) 
                lock (_mutex)  
                    if (!_isInitialised) 
                        Application_Start();
        }
        /// <summary>
        /// Application start-up code will be executed once here
        /// </summary>
        private void Application_Start()
        {
            _isInitialised = true;
            // add code
        }