views:

42

answers:

1

Why would Application_Init fire twice when starting debugging in VS2008/Casini?

Yeah, It's happening in global.asax. Seems fairly random though, only happens once in a while.

+2  A: 

I assume you're referring the the Global.asax file in an ASP.NET MVC application. Notice that your global.asax extends System.Web.HttpApplication eg:

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        // (snip)
    }

    protected void Application_Init()
    {
        // Why is this running twice?
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    }
}

Basically multiple HttpApplication instances are being instantiated to serve multiple incoming HTTP requests. Once the request is finished, the HttpApplication instance goes back into a pool to be reused again, similar to database connection pooling.

You can't predict how many HttpApplication instances will be created, basically the ASP.NET worker process will create as many as it needs to fulfill demand from HTTP requests hitting your web app. Your Application_Init() is getting called twice because 2 HttpApplication instances are being created, even though it's just you running your website. It could be that you have references to other server-side resources in your HTML being pulled in (JavaScript files, CSS etc.), or maybe an Ajax Request.

If you want to guarantee code is only run once, then put it in the Application_Start() method in your Global.asax. Or use a Bootstrapper

Sunday Ironfoot
Thanks............
UpTheCreek