Search code examples
asp.net-mvc-3asp.net-4.0webactivator

Preferred way to setup and run code in Application_Start


What is the preferred way to hook up and run some code in Application_Start and Application_Endrequest without having to put the code in the MvcApplication class each time?

Maybe there is an event, an attribute or something I can hook up in asp.net 4?


Solution

  • That is not a correct statement that "lets you hook up code to run before the application gets compiled."

    WebActivator classes that you create actually get compiled into the assembly, but allow you to hook into 3 events at run time:

    1.) PreApplicationStartMethod 2.) PostApplicationSTartMethod 3.) ApplicationShutdownMethod

    From David Ebbo's desciption:

    "WebActivator is a NuGet package that allows other packages to easily bring in Startup and Shutdown code into a web application. This gives a much cleaner solution than having to modify global.asax with the startup logic from many packages."

    Using WebActivator is not limited to startup code for just other packages, it can also be used for startup code (bootstrapping) for your application as well.

    For instance, I use it to set up and configure my Unity dependencies, my Combres setup, and my 51DegreesMobi setup in a recent project I completed using MVC3. It allows me to have a separate class file for each of those without cluttering up or entering a single line of code in Global.asax.

    It is also a much better alternative to the .NET 4 PreApplicationStartMethod in that you can have many classes that have the WebActivator.PreStartupMethod and they will ALL run prior to App-Start, as opposed to the .NET 4 attribute in which I believe you're only allowed to use once.