Order of execution of the absolute earliest places to run code in ASP.NET
asp.net, lifecycle
Solution
Static constructors and static field initialization is determined by the runtime, not ASP.NET. Eric Lippert recently posted a great four-part blog series detailing how they work.
As for the rest of the items you mentioned, methods marked with the `System.Web.PreApplicationStartMethodAttribute` are executed first. According to the MSDN documentation for this attribute, there is no guarantee of the order in which these methods are called.
According to a blog post by Phil Haack, this attribute gives developers the opportunity to call two other methods during the application's startup: `BuildProvider.RegisterBuildProvider` and `BuildManager.AddReferencedAssembly`. The MSDN documentation for `BuildManager.AddReferenceAssembly` states that this method can only be executed during the Application_PreStartInit stage of the application, which suggests that's when all methods marked by the `System.Web.PreApplicationStartMethodAttribute` are executed.
WebActivator uses the framework's `PreApplicationStartMethodAttribute` to hook into the application's startup. Once called, it will search for and execute all methods marked by the `WebActivator.PreApplicationStartMethodAttribute` before it dynamically registers an HttpModule that will later invoke all methods marked by the `PostApplicationStartMethodAttribute` - after Application_Start has been called in the HttpApplication class.
So, to summarize, the order is:
- Web.config is read into memory
- Methods marked with a `PreApplicationStartMethodAttribute`
- HttpApplication.Application_Start
- Methods marked with `WebActivator.PostApplicationStartMethodAttribute`
Problem
There are numerous places you can have initialization code be executed in ASP.NET: - web.config is processed - WebActivator `PreApplicationStartMethod` - WebActivator `PostApplicationStartMethod` - Global.asax `Application_Start` What is the ordering of these occurences? Are there any other additional items that should be to this list? Edit: Since it was mentioned that statics are relevant to first invocation location, I'm going to break this up for them Foo class that is used in a WebActivator `PreApplicationStartMethod` - static constructor - static readonly field Bar class that is used in a WebActivator `PostApplicationStartMethod` - static constructor - static readonly field Baz class that is used in a Global.asax `Application_Start` - static constructor - static readonly field For clarity purposes, suppose that in the above examples each of those depends on the Foo/Bar/Baz class being used in the location and that the class contains a static constructor and static readonly field.