This project is read-only.

Disposing objects or the container all togather

Feb 11, 2013 at 5:11 PM
I have moved newly to SimpleInjector, and i would like to know if it is possible to dispose the whole container, and in case that is possible, does it lead to disposing the disposable services registered with that container.
Feb 11, 2013 at 5:52 PM
Edited Feb 11, 2013 at 5:52 PM
The container does not implement IDisposable. This is a conscious design decision. The advised way of working with Simple Injector (and any DI framework for that matter) is to have a single Container instance for the lifetime of the application. In that case singleton instances will also live for the lifetime of the application, and there is no real need in disposing them. Or at least, those objects can be designed in such way (with a finalizer or SafeHandle for instance) that any unmanaged resources get cleaned when the AppDomain ends.

The amount of services that need to be disposed should be rather small. If your configuration has many components that need to be disposed, you might be missing some general abstraction. Especially when dealing with dependency injection, since dependencies are passed in from the outside (constructor injection) the consuming component doesn’t take ownership and doesn’t have to implement IDisposable, even though the dependency might implement it.

There are several scoped lifestyles that allow you to deterministically dispose instances with that lifestyle. Per Web Request and Per WCF Operation are implicitly scoped (the framework will create a scope for you) and Per Lifetime Scope is explicitly scoped (you will need to start and end the scope). For most cases, those lifestyles will be sufficient.

If you still need any app shutdown logic you need to implement this yourself.

And if you’re creating many container instances (for instance one per request), I would urge you to stop doing that, since this can have great impact on the performance of the application. This not only holds for Simple Injector, but this holds for most (if not all) DI containers.
Marked as answer by dot_NET_Junkie on 11/5/2013 at 7:34 AM
Feb 11, 2013 at 6:01 PM
It's been a long time since i have seen such Detailed, Accurate, Nicely Explained, Awesome answer.
Thank you very much.