How to initialize and de-initialize only one time during application life cycle in ASP.NET MVC

Viewed 458

I have one static class that I need to initialize some code during the class used for the first time and de initializes when the application process dies. Actually, the init method calls the native C++ apis using the PInvoke method. I know I can use static constructor but now I need to call a native de-init method at the end,

public static class MyClass
{
    static MyClass()
    {
        MyInitFirstTime();
    }        
2 Answers

Instead of a static class, you can use the Application_Start and Application_End "special methods" as documented by Microsoft.

The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.

Another option is to overwrite the HttpApplication.Dispose method or the Disposed event. If you decide to overwrite Dispose(), don't forget to invoke the base class Dispose() method.

There isn't any native method for static classes, but you can use AppDomain DomainUnload event instead:

public static class MyClass
{
    static MyClass()
    {
        AppDomain.CreateDomain("dummy").DomainUnload += CurrentDomain_DomainUnload;

        MyInitFirstTime();
    }

    private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
    {
        // Free resources
    }
}
Related