Search code examples
asp.netglobal-asaxapplication-start

ASP.Net: Can I fire "Application_Start" code programmatically?


At some point during execution of the project, I need to reset the application or at least re-run "Application_Start" code. Is there a way to issue an application-restart command or fire "Application_Start" code in global.asax programmatically?


Solution

  • There are two ways I can think of.

    A really easy way is to force a unload of the AppDomain, and then IIS will detect the unload, and re-load (recycle) the app pool for you.

    So, say behind some admin form on the site you could have this code:

        System.Web.HttpRuntime.UnloadAppDomain()
    

    Another approach would be to simply move out all of your code from the Global.asax file, say like this:

    Sub Application_Start(sender As Object, e As EventArgs)
    
        MyStartCode()
    
    End Sub
    
    
    Public Sub MyStartCode()
    
        Debug.Print("Application startup code")
    
    
        ' Fires when the application is started
        RouteConfig.RegisterRoutes(RouteTable.Routes)
        BundleConfig.RegisterBundles(BundleTable.Bundles)
    
    
    End Sub
    

    So, simply move out all of the code from the Application_Start (you in 99% of cases don't care nor need the event sender and args anyway).

    So, then your button on the admin page could thus do this:

        Dim MyGlobal As New Global_asax
    
        MyGlobal.MyStartCode()
    

    So, you create an instance of that object, and simply call your public routine of which you moved all your startup code into.

    So, either of the above two approaches should work.