views:

568

answers:

1

During practice of customizing VirtualPathProvider, I found that it the custom VirtualPathProvider can be registered in Global.asax or in AppInitialize method according to MSDN http://msdn.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx. However, MSDN doesn't clearly describe the method AppInitialize.

Does any static AppInitialize method in App_code folder will be automatically invoked by ASP.NET runtime at start up?

+4  A: 

While there is precious little documentation about the AppInitialize() method, you are correct in your assumption that any class in your App_Code folder that contains a method signature like this:

public static void AppInitialize()

will be invoked when the Asp.Net application starts up. Remember that App_Code is a special folder to Asp.Net and everything inside there is treated a little differently. Good luck finding documentation on all the little quirks (like the aforementioned) of the App_Code folder.

Another thing to remember however is that only one class can contain a signature for the AppInitialize() method or else you will get a compiler error at runtime similar to this:

The AppInitialize method is defined both in 'App_Code.SomeClassOne' and in 'App_Code.SomeClassTwo'.

So while this is perfectly valid:

public class SomeClassOne
{
    public static void AppInitialize()
    {
        HostingEnvironment.Cache["InitializationTimeOne"] = DateTime.Now;
    } 
}

This will generate the compiler error I mentioned above:

public class SomeClassOne
{
    public static void AppInitialize()
    {
        HostingEnvironment.Cache["InitializationTimeOne"] = DateTime.Now;
    } 
}

public class SomeClassTwo
{
    public static void AppInitialize()
    {
        HostingEnvironment.Cache["InitializationTimeTwo"] = DateTime.Now;
    } 
}

I hope this clears things up a bit for you :)

Josh