There's basically two ways I've seen this is handled:
- When you resolve a service to an object that implements IDisposable, the container will remember this. When you dispose of the container, that service will be disposed of as well.
- When you resolve a service, what you get back is not just the service object itself, but you also get a wrapper object, that implements IDisposable, and requires you to dispose of it. When you do, it will also know what to do with the actual service object you requested.
Of the 2, the third is the most common:
- When you resolve to a service that implement IDisposable, don't give a damn and just leave the service object floating until garbage collection handles it.
This is basically just the IoC framework not providing you with any means at all to handle this problem. If you do, that's your case, not the framework's responsibility.
But, hang on, the problem gets more hairy when you consider it.
What if the service object you get back is a singleton? Even though it might implement IDisposable, should you dispose of it? How do you know? How can you find it? Can you find out? At the point when you say "I know this service will be a singleton", you've basically taking a sort of dependency and implemented special code to handle it. The point of IoC is to be able to substitute services without changing the code that consumes them. IDisposable throws a big spanner in the works of this process.
In short, the best solution with most of todays IoC frameworks is to implement services that doesn't implement/require IDisposable.