title: How do you force the IIS Application Pool to restart whenever the App Domain is reloaded?
body: <p>We have an ASP.NET MVC 4 application that links to legacy native code. The problem is that this legacy code has global statics that are constructed at startup, but because native code knows nothing about App Domains, that code is not re-initialized when the App Domain is reloaded. This causes incorrect behaviour or crashes in our app until the Application Pool process is restarted.</p>
  
  <p>Because of this, I would like to force the Application Pool to recycle whenever our application's App Domain is recycled. Is there a setting in IIS for this, or is there code that I can call in my application as the domain is being unloaded?</p>
  
  <p>Some info on my setup,</p>
  
  <ol>
  <li>ASP.NET MVC 4 application</li>
  <li>IIS 7.5, but I can move to 8 if required</li>
  <li>I can ensure that there is one application per Application Pool, so I will not be affecting other applications.</li>
  </ol>
  
  <p><strong>Update</strong></p>
  
  <p>Based on the answer below, I hooked up to the AppDomain unload event and used code similar to the following to recycle the Application Pool.</p>
  
  <pre><code>try
  {
     // Find the worker process running us and from that our AppPool
     int pid = Process.GetCurrentProcess().Id;
     var manager = new ServerManager();
     WorkerProcess process = (from p in manager.WorkerProcesses where p.ProcessId == pid select p).FirstOrDefault();
  
     // From the name, find the AppPool and recycle it
     if ( process != null )
     {
        ApplicationPool pool = (from p in manager.ApplicationPools where p.Name == process.AppPoolName select p).FirstOrDefault();
        if ( pool != null )
        {
           log.Info( "Recycling Application Pool " + pool.Name );
           pool.Recycle();
        }
     }
  }
  catch ( NotImplementedException nie )
  {
     log.InfoException( "Server Management functions are not implemented. We are likely running under IIS Express. Shutting down server.", nie );
     Environment.Exit( 0 );
  }
  </code></pre>