tags:

views:

78

answers:

1

How Many Times Does an ASP .NET Application Start?

I want to run something once per AppDomain (specifically RegisterRoutes). If I put the code I want to execute in the global.asax in Application_Start, everything's good (or so it seems) and the code seems to only execute once.

But If I have a custom HTTP Module registered in the web.config that does the following:

public class SomeHttpModule:IHttpModule
{
    public void Init(HttpApplication context)
    {
        new SomeRunner().Run();
    }

    public void Dispose()
    {
    }
}

public class SomeRunner
{
    private static object syncLock = new object();
    private static bool hasRun;

    public void Run()
    {
        lock(syncLock)
        {
            if (!hasRun)
            {
                hasRun = true;
                RegisterRoutes();
            }
        }
    }

    public void RegisterRoutes()
    {
        // Register MVC Routes
    }
}

When I hit "go" in Visual Studio, my debugger stops at my breakpoint at the first line of the Run method...but lo and behlold if I check the RouteTable.Routes collection...the MVC routes have already been registered (meaning RegisterRoutes must have already been called)...even though hasRun is false!

Is this some sort of oddness running in Visual Studio debugging an IIS website? I know that IIS can host two HttpApplications in one AppDomain and that would have SomeHttpModule get Init'd twice in the same AppDomain...right? But how would my static bool hasRun still possibly be false???

Thanks.

A: 

A web application can be started many times. The application can be closed down whenever IIS thinks that it's not used, and when the next request comes in the application will start again.

Also, the application might be set to recycle daily, in that case it would start at least once a day.

I'm not sure why the application is started twice when you are debugging it, but it might have something to do with how the debugger is attached to the process.

The reason that the static variable doesn't survive from one instance of the application to the next, is that they are separate instances. When the application starts again, it starts with it's own set of variables. It starts in a completely new virtual address space, so there is nothing left from the previous instance.

Guffa
but then why is RouteTable.Routes persisting, but not hasRun?
JeffN825
For some reason, I can't reproduce this in release mode...I think it may be a debugging oddity... I will accept this answer though, so as to close the question.
JeffN825