Shutdown WPF Application From Inside a Module

Topics: Prism v2 - WPF 3.5
Sep 24, 2009 at 4:23 PM

I have a need to shutdown the application from within a module.  I was thinking that the Bootstrapper could stuff the Application.Current into the Unity container and I could call Shutdown on that, however that leads to tight binding.  Theoretically my module could throw a SecurityException from within Initialize and I could catch that but from where?  Ideas?

Sep 24, 2009 at 4:53 PM

Can the bootstrapper respond to commands or events?


Sep 24, 2009 at 6:09 PM


You can use the following code to close the shutdown the application:


Brian Noyes blogged about Supporting Graceful Shutdown and Saving on Close From a WPF Prism App some time ago. You might find some useful ideas in that post.

Please let me know if this helps.

Damian Schenkelman

Sep 25, 2009 at 2:36 PM


  I saw that article while Google'ing around.  Here is what I did.  I created an CompositePresentationEvent derived class, AuthenticationEvent.

    public class AuthenticationEvent : CompositePresentationEvent<AuthenticationEvent> {

        public string UserCode { get; private set; }
        public bool Success { get; private set; }

        public AuthenticationEvent() {

        public AuthenticationEvent(string userCode, bool success) {
            UserCode = userCode;
            Success = success;

After reviewing the code for the UnityBootstrapper baseclass, I saw that an IEventAggregator was added to the container prior to the call to InitializeModules.  Therefore, in my derived Bootstrapper class, I overrided the InitializeModules method like this:

        protected override void InitializeModules() {

            var eventAggregator = Container.Resolve<IEventAggregator>();
            var authenticationEvent = eventAggregator.GetEvent<AuthenticationEvent>();
            authenticationEvent.Subscribe(ShutdownApplication, ThreadOption.UIThread);


and then in my event handler I have this:

        private void ShutdownApplication(AuthenticationEvent e) {
            LoggerFacade.Log(String.Format("Login {0} for: {1}", e.Success, e.UserCode), Category.Debug, Priority.Low);

            if (e.Success)
            else {
                Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

Note that I moved the _shell.Show() from the CreateShell method to here.  My login box is using CredUI, so I have no need for the Shell unless the user authenticates.  Also, during the authentication process, which occurs inside my SecurityModule, permissions are stuffed into a custom IPrincipal object and then assigned to the Thread.CurrentPrincipal. I can then later use that info to dynamically load modules based on user permissions using the IModuleManager.

This works like a charm.  The whole idea was to shutdown the application in the application and not inside a module.