When AppInitialize method get invoked in ASP.NET?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 🙂


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x