ASP.NET API IIS 池回收上的 DI(简单注入器)空引用

ASP.NET API DI (Simple Injector) null reference on IIS pool recycle

我之前发布了另一个问题,但经过一些观察后,我缩小了范围,确定可能是什么导致了我的问题。基本上,一旦 IIS 应用程序池被回收,我的依赖项注入(最终通过创建 NWatchApplication 扫描某些 DLL)就会失败。 INWatchApplication 是 Web API 项目的依赖项。

以下是Global.asax的内容:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    var webApiContainer = new Container();
    webApiContainer.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
    RegisterTypes(webApiContainer);
    webApiContainer.RegisterWebApiControllers(GlobalConfiguration.Configuration);
    webApiContainer.Verify();

    GlobalConfiguration.Configuration.DependencyResolver =
        new SimpleInjectorWebApiDependencyResolver(webApiContainer);
}

private void RegisterTypes(Container container)
{
    var virtualPath = HostingEnvironment.ApplicationVirtualPath.Substring(1);
    string baseName = null;

    if (!string.IsNullOrEmpty(virtualPath)) {
        baseName = HostingEnvironment.SiteName + "_" + virtualPath;
    } else {
        baseName = HostingEnvironment.SiteName;
    }

    var nWatchApp = new NWatchEntityApplication(GetNWatchConfig());
    Trace.Listeners.Add(new DevOps.Diagnostics.DevOpsLogTraceListener(baseName));
    container.RegisterSingleton<INWatchApplication>(nWatchApp);
    container.Register<NWatchDbContext>(() => nWatchApp.GetDbContext(), Lifestyle.Scoped);
}

private INWatchConfiguration GetNWatchConfig()
{
    Configuration rootConfig =
        System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
    return new NWatchSystemConfiguration(rootConfig);
}

我读过各种博客和帖子,讨论动态加载的 DLL 似乎是个问题,因为当 IIS 回收池时,它们不会复制到 AppDomain。 (我在这里可能完全错了,但这是我的怀疑)。

如何确保所有可能已加载的 DLL(当应用程序首次部署到 IIS 时)即使在回收后仍继续可供应用程序使用?

var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>();

在Global.asax里面放入Application_Start()好像问题解决了!