When AppInitialize method get invoked in ASP.NET?

我们两清 提交于 2019-11-28 08:18:41

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!