We are currently evaluating if we could use Ninject for future projects. One condition is, that the libary should NOT force us to call the Dispose method. So, is it really necessary? Will not calling it result in memory leaks and other ugly stuff?
-
You are never forced to call dispose. Not calling it never causes leaks, the finalizer cleans up after you. You just run fat, laziness you can easily work around by buying more expensive computers. – Hans Passant May 25 '12 at 13:39
2 Answers
I don't think Ninject, being a purely managed solution, would have any problems with memory leaks or other things if you don't call Dispose(). Especially since you would only be calling the kernel's Dispose() method as one of the last things you do before terminating an application, so memory would be reclaimed by the GC or the OS' process isolation anyway.
The reason you would want an IoC container that lets you call Dispose() is that it will call Dispose() on any service providers that are implementing IDisposable. Which is a useful feature, I believe, since service providers might own unmanaged resources or need to wait for asynchronous operations to be completed (or at the very least abort them in an orderly fashion).
I'd go as far and wager that this is the reason behind most IoC containers that implement IDisposable on their kernel/provider/locator class.
Why is having Dispose() on an IoC container a problem for you? So far, I've always found an appropriate place to call it, be it in a console application, a XAML-based WPF application or an Xbox game.

- 9,444
- 8
- 42
- 50
-
Dispose is not a problem for me, but obviously a problem for some other guys. – Display Name May 25 '12 at 12:31
-
You call Dispose on the kernel exactly once in your entire application. Where is the problem? – Remo Gloor May 25 '12 at 13:03
-
Then I believe it would be a good idea to find out what the concerns of those other guys are. In case they consider IDisposable a code smell, you already have good reasoning here as to why it makes sense from a design perspective. – Cygon May 25 '12 at 13:48
You could configure Ninject in a way to help you with Dispose. It's depends on what scope and what strategy do you use with Ninject. For example:
- Ninject disposes every Disposable object that has another scope other than
InTransientScope
as soon as the scope object to which the created object is tied is collected by GC., - Singletons will be disposed when kernel is disposing,
- Also you could use
OnDeactivation
method orInScope(x => new DisposableStrategy())
- Or use
StandardScopeCallbacks.Request
to make your object dispose withHttpRequest
. This is useful for web applications.