MVC Pre-Application Start Code

MVC has a file called PreApplicationStartCode.cs which contains this code:

namespace System.Web.Mvc {

using System.ComponentModel;

using System.Web.WebPages.Scope;

[EditorBrowsable(EditorBrowsableState.Never)]

public static class PreApplicationStartCode {

private static bool _startWasCalled;

public static void Start() {

// Guard against multiple calls. All Start calls are made on same thread, so no lock needed here

if (_startWasCalled) {

return;

}

_startWasCalled = true;

System.Web.WebPages.Razor.PreApplicationStartCode.Start();

System.Web.WebPages.PreApplicationStartCode.Start();

ViewContext.GlobalScopeThunk = () => ScopeStorage.CurrentScope;

}

}

}

This code is called when the System.Web.Mvc.dll assembly is loaded due to this line in the MVC AssemblyInfo.cs file:

[assembly: PreApplicationStartMethod(typeof(System.Web.Mvc.PreApplicationStartCode), "Start")]

The PreApplicationStartCodeAttribute tells the .NET run-time to run the specified code when the application is loaded.

The Start method on the PreApplicationStartCode class calls the Razor and the Web Pages startup code, and ensures that this startup code executes only once.

The Razor startup code simply registers the .cshtml and .vbhtml build providers.

The Web Pages startup code does the following:

    1. Registers the cshtml and vbhtml file types.

    2. Disables the ability of the ASP.NET PageParser to use long strings as resources by setting that class’ static EnableLongStringsAsResources property to false. (From MSDN: By default, the ASP.NET page parser converts literal strings that contain 256 or more characters into a temporary resource string. This property can be set to false in order to disable this behavior and instead to write the literal string directly to the response stream. This property can only be set in the Global.asax file before the PreApplicationStart event occurs. This property can be read at any time.)

    3. Registers the Web Pages HTTP module.

    4. Sets the ScopeStorage class’ current scope storage provider to an instance of the AspNetRequestStorageProvider class.

...