IDisposable and Dependency Injection Containers

Recently I got feedback from Nick Randolph, another device developer MVP, regarding the OpenNETCF.IoC framework and handling the lifecycle of IDisposable objects (well we taked about a few things, but this is the one I tackled first).  The problem is that if you add an IDisposable object to any DI container (be it OpenNETCF.IoC, Unity, Ninject or whatever) the container knows nothing about the object’s Disposed state.  Unfortunately the IDisposable interface doesn’t expose an IsDisposed property or OnDisposed event. 

SO what, exactly, is the problem?  Well, let’s assume we create an IDisposable object and add it to the DI container.  AT some point later, we’re done with the object, so we call Dispose.  Well that internally releases the object’s native resources, but the object itself still has a root (the reference from the container) and so the GC will never actully collect the object and its managed resources.  On an embedded device this could be a problem.

The solution that we came up with is to create a wrapper for IDisposable objects and a new set of methods for the container for adding.  So now you can do something like this:

var instance = RootWorkItem.Items.AddNewDisposable<MyDisposableType>();

Now instead of this returning an instance of MyDisposableType, it returns a container object that holds it.  You access the MyDisposableType object itself via the Instance property of the container, which requires some small code work on the consumer’s part, but the nice thing is that when you call Dispose on that container, it in turn calls Dispose on the contained instance *and* it removes the object from the DI container so the GC can do it’s work on the object.

I’ve not rolled a new framework release with these changes because they really are just a proposed solution for now.  If you’re interested, go ahead and pull the latest code from the source code page (change set 32718) on the project site and give it a try.  There are a load of new unit tests that show the general idea on usage.

1 thought on “IDisposable and Dependency Injection Containers”

  1. Hello Chris
    Wouldn’t it be consistent if the DisposableWrappedObject
    would also implement IDisposable? Because the container itself carries an IDisposable and must therefore be declared IDisposable (as FxCop would demand).



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s