如何强制IIS应用程序池在重新加载应用程序域时重新启动?

10
我们有一个ASP.NET MVC 4应用程序,链接到遗留的本地代码。问题在于这些遗留代码有全局静态变量,在启动时构造,但是由于本地代码对应用程序域一无所知,因此当应用程序域重新加载时,该代码不会被重新初始化。这导致我们的应用程序出现不正确的行为或崩溃,直到应用程序池进程重启。
因此,我想在我们的应用程序的应用程序域被回收时强制应用程序池进行回收。在IIS中是否有此设置,或者在卸载域时是否可以在我的应用程序中调用代码?
一些关于我的设置的信息:
1. ASP.NET MVC 4应用程序 2. IIS 7.5,但如果需要,我可以移动到8 3. 我可以确保每个应用程序池只有一个应用程序,因此不会影响其他应用程序。
更新:
根据下面的答案,我连接到了AppDomain卸载事件,并使用类似于以下内容的代码来回收应用程序池。
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 );
}
3个回答

3

一种更加粗暴的方法是调用Process.GetCurrentProcess().Kill()。虽然不太优雅,但如果您的网站有自己的应用程序池并且不在乎当前请求被暴力终止,那么这是相当有效的!


3

以下是你分享的代码的简化VB版本。此版本使用For循环而不是LINQ查询。另外,要使用Microsoft.Web.Administration,您必须从c:\ windows \ system32 \ inetsrv导入DLL。

Imports System.Diagnostics
Imports Microsoft.Web.Administration

Dim pid As Integer = Process.GetCurrentProcess().Id
Dim manager = New ServerManager()
For Each p As WorkerProcess In manager.WorkerProcesses
    If p.ProcessId = pid Then
         For Each a As ApplicationPool In manager.ApplicationPools
             If a.Name = p.AppPoolName Then
                 a.Recycle()
                 Exit For
             End If
         Next
         Exit For
    End If
Next

2

谢谢,那不完全是我需要的,但它指引了我正确的方向。 - Rob Prouse
@RobProuse 那你当时做了什么? - George Mauer
George,我把我在更新中编写的代码放在了应用程序域卸载事件处理程序中,这个处理程序是我在启动时注册的。最终,我将我们的代码转换为自托管的ASP.NET应用程序,以便我们可以管理应用程序和应用程序域的生命周期。 - Rob Prouse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接