Dutton

How to allow Prism Unity modules to properly Dispose() on Application shutdown

I have a Prism application which uses a Unity DI container to load a bunch of modules which represent various elements of my application.

I recently needed to perform some clean-up in one of my modules when the application exits. Normally this is something I would do with an IDisposable implementation, but in a Prism/Unity setup Dispose never gets hit on the module code.

Here's how I got around it:

First I created a custom Event to allow me to signal my modules that the container is closing:

public class ApplicationExitEvent : CompositePresentationEvent<string> { }

Then in my bootstrapper I implement IDisposable and fire the event in my Dispose() method:

public void Dispose()
{
  var eventAggregator = Container.Resolve<IEventAggregator>();
  if (eventAggregator != null)
  {
    eventAggregator.GetEvent<ApplicationExitEvent>().Publish("");
  }
}

Then in my module's Initialize() method I subscribe to this event:

EventAggregator.GetEvent<ApplicationExitEvent>().Subscribe((o) => Dispose(), true);

And put whatever cleanup code I need in my module's Dispose method. Done!


Share this: