Reputation: 12458
When dealing with an IOC container like Autofac in a Web or Api solution, you see a lot of implimentation code like this:
protected void Application_Start()
{
///etc..
this.container = builder.Build();//returns IDisposable instance
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
//etc..
}
protected void Application_End()
{
container.Dispose();
}
See that on Application_End the container is being disposed explicitly.
Great, but is that really necessary?
Upvotes: 3
Views: 997
Reputation: 47570
Great, but is that really necessary?
Yes, that's the best practice. Dispose all IDisposable instances when you finish.
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?
The advantage is, Disposing will suppress the finalization (if you container has a implemented finalization). So, the garbage collector will dispose it sooner as it doesn't have to go to the finalization queue.
Note:
And also note that when you are disposing Autofac LifetimeScope
, it will execute the Dispose
for all of it IDisposable instances. For instance, if you have created your container
using Autofac and you are disposing the Autofac's LifeTimeScope
when you finish, you may not have to Dispose the container
manually.
Upvotes: 2