I am trying to execute some code in the application start of an HTML Module. Since the Init() gets fired multiple times, is there a reliable flag to tell me if the application started or not?
public class Module : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
//clean-up code here.
}
public void Init(HttpApplication context)
{
//PROCESS ON APPLICATION START EVENT
this.OnApplicationStart(context);
}
#endregion
public void OnApplicationStart(HttpApplication context)
{
if (!application started??) //FRAMEWORK FLAG?
//DO SOMETHING
}
}
You could use a flag:
public class Module : IHttpModule
{
private static bool isStarted = false;
private static object syncRoot = new object();
public void Dispose()
{
//clean-up code here.
}
public void Init(HttpApplication context)
{
if (!isStarted)
{
lock (syncRoot)
{
if (!isStarted)
{
//PROCESS ON APPLICATION START EVENT
this.OnApplicationStart(context);
isStarted = true;
}
}
}
}
public void OnApplicationStart(HttpApplication context)
{
//DO SOMETHING
}
}
As a better alternative to using HttpModules to perform this task if you are targetting .NET 4.0 or later I would recommend you using WebActivator
which is a very handy package based on Microsoft.Web.Infrastructure
allowing you to subscribe to events such as Application_Start
in separate libraries.
For example, simply put the following code in a class library:
[assembly: WebActivator.PreApplicationStartMethod(typeof(WebAppInitializer), "Start")]
namespace FooBar
{
public static class WebAppInitializer
{
public static void Start()
{
// PROCESS ON APPLICATION START EVENT
}
}
}
and then referencing the class library in your ASP.NET application is all it takes.
You could also use this handy WebActivator to perform dependency injection into your HttpModules and self register them without the need to add them to web.config. Phil Haack wrote a nice blog post
on this topic if you are interested.