When AppInitialize method get invoked in ASP.NET?

前端 未结 1 1100
执念已碎
执念已碎 2020-12-09 09:16

During practice of customizing VirtualPathProvider, I found that it the custom VirtualPathProvider can be registered in Global.asax or in AppInitialize method according to M

相关标签:
1条回答
  • 2020-12-09 10:02

    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 :)

    0 讨论(0)
提交回复
热议问题