Disposable Unity Module

Aug 17, 2009 at 9:44 PM

What is the proper way to implement IDisposable using Unity container? I have modules that will spawn threads. When the application exists I'd like to be able to dispose of those threads if active. Thanks.

Aug 20, 2009 at 1:09 PM

I'm not sure if this is the correct way, but one approach could be to implement IDisposable on your modules.  The modules could then take care of tearing down the threads that they start during Dispose().  As each module is Initialized(), it could register itself in the container using a ContainerControlledLiftime.  Using this method, the lifetime manager will dispose the module  when the container is disposed and at that point your modules could tear down the threads they've created.

Aug 20, 2009 at 3:02 PM

Thanks. That was my first approach but the Unity container does not seem to call Dispose() when the modules are being released. I registered the module with the ContainerControlledLifetimeManager and defined the module to implement IDisposable. Dispose() was not called during app shutdown.

Aug 20, 2009 at 3:13 PM

Are you disposing your Container on shutdown?   If not, then the container will never dispose it's managed objects, I don't think.

Aug 20, 2009 at 3:36 PM

I am not doing anything special regarding the Unity container. I was under the impression that it is part of the Bootstrapper which is what I'm instantiating in the App class. I expect that the container is then released when the Bootstrapper is destroyed by the App on shutdown. I'm suspecting that perhaps I'll need a custom LifetimeManager. Thanks again for your reply.

Aug 21, 2009 at 12:50 PM

Jeremy, thanks for your help. I tracked it down. Just as you said. The container is exposed from the bootstrapper and implements IDisposable. I found a convenient place to hook into the app shutdown and called Dispose on the container. The container then called Dispose on the objects which I had defined to implement IDisposable.