在 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/