c# - 如果无论如何都要结束,是否有必要在 Application_End 上进行处理?

标签 c# asp.net-mvc asp.net-web-api autofac

在 Web 或 Api 解决方案中处理像 Autofac 这样的 IOC 容器时,您会看到很多这样的实现代码:

protected void Application_Start()
{
    ///etc..
    this.container = builder.Build();//returns IDisposable instance
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    //etc..
}

protected void Application_End()
{
    container.Dispose();
}

看到在 Application_End 上容器被显式处理。

很好,但这真的有必要吗?

  • 我们不是在讨论即将以任何方式结束的 Web 应用程序吗? 案件?
  • 当然,这意味着将为所有调用 Dispose 未处理的对象还在乱跑?
  • 是否有正当理由 或以这种方式显式调用处置的好处?

最佳答案

Great, but is that really necessary?

是的,这是最佳实践。完成后释放所有 IDisposable 实例。

Aren't we talking about a web application that is about to end in any case? Surely, that means that Dispose will be called for ALL un-Disposed objects still kicking around? Is there any valid reason or benefit for calling the dispose explicitly in this way?

优点是,Disposing 会抑制终结(如果您的容器已实现终结)。因此,垃圾收集器将更快地处理它,因为它不必进入终结队列。

注意:

另请注意,当您处理 Autofac LifetimeScope 时,它将为所有 IDisposable 实例执行 Dispose。例如,如果您使用 Autofac 创建了 container,并且在完成后要释放 Autofac 的 LifeTimeScope,则您可能不必释放 container 手动。

关于c# - 如果无论如何都要结束,是否有必要在 Application_End 上进行处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34035088/

相关文章:

c# - SmartEnumerable 和 Regex.Matches

c# - 如何从第一项之外的 foreach 枚举

c# - WCF 与 ASP.NET Web API

asp.net-mvc - Visual Studio 2013 文档大纲工具始终为空

c# - Styles.Render 在 View 中

c# - Newtonsoft.Json - 将通用对象反序列化为包装类

c# - 如何找出正在运行的用户网络应用程序?

c# - 将单行从多维数组复制到新的一维数组

c# - 太多的函数调用

c# - 使用最小起订量验证列表