Autofac - 我是否需要在 MVC global.asax 中手动处理 IContainer?

JAM*_*EME 4 c# asp.net-mvc autofac

我似乎无法在文档或 stackOverflow 中找到这个问题的答案(尽管我可能忽略了它)。我很好奇我是否应该手动处理 ContainerBuilder 提供的 IContainer?

这是来自 Remember.Web 的代码示例:

//etc..
IContainer container = builder.Build();//returns IDisposable instance
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
//etc..
Run Code Online (Sandbox Code Playgroud)

但我很好奇它是否应该是这样的:

public class MvcApplication : HttpApplication
{
    private IContainer container;//not necessary..?

    protected void Application_Start()
    {
        ///etc..
        this.container = builder.Build();//returns IDisposable instance
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        //etc..
    }
    protected void Application_End()
    {
        container.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我忽略了某些内容,请务必指出正确的文档,谢谢!

Pet*_*old 5

使用一次性物品时,模式是您应该始终在使用完对象后立即将其处理掉。所以我会说是的,对此要明确。文档和示例应该提到这一点。

如果您不手动处置容器,它将在 appdomain 卸载后的一段时间由 GC 释放(连同任何包含的实例)。

注意:正如@Steven 提到的,Dispose垃圾收集期间不会调用方法。因此,您在Dispose方法中可能具有的任何逻辑都不会被执行。所以处置容器是否有意义取决于容器所持有的实例。再次,显式调用Dispose在Application_End将确保没有这样的逻辑丢失。

也就是说,如果您的容器中有需要处理的服务,您可能希望将这些注册移动到请求范围。这确保一次性实例仅与请求一样长。请求生命周期范围由 Autofac 集成模块处理,因此您无需采取任何行动来进行清理。