如何在bootstrapper类仍在运行时关闭应用程序?

时间:2012-02-10 23:33:57

标签: c# wpf prism bootstrapper

我正在使用Prism UnityExtensions引导程序类来启动我的WPF应用程序。如何在unityextensions bootstrapper仍在运行时关闭应用程序?

请参阅下面的我的引导程序类。 SomeClass对象可能会抛出自定义异常(致命)。如果抛出自定义异常,我需要关闭该应用程序。我正在使用Application.Current.Shutdown()来关闭应用程序。

但是,引导程序代码继续运行,并且在CreateShell()方法中设置datacontext时出现“ResolutionFailedException未处理”异常错误。显然,由于catch块,SomeClass方法和接口未在容器中注册。

在调用Application.Current.Shutdown()之后,似乎引导程序代码继续运行。我需要在关闭调用之后立即停止引导程序代码。

如何在不创建ResolutionFailedException的情况下关闭应用程序的任何想法?

  

ResolutionFailedException异常详情 - >   依赖项的解析失败,type =“SomeClass”,name =“(none)”。   在解决时发生异常:   异常是:InvalidOperationException - 当前类型SomeClass是一个接口,无法构造。你错过了类型映射吗?

public class AgentBootstrapper : UnityBootstrapper
{
  protected override void ConfigureContainer()
  {
     base.ConfigureContainer();

     var eventRepository = new EventRepository();
     Container.RegisterInstance(typeof(IEventRepository), eventRepository);

     var dialog = new DialogService();
     Container.RegisterInstance(typeof(IDialogService), dialog);

     try
     {
        var someClass = new SomeClass();
        Container.RegisterInstance(typeof(ISomeClass), SomeClass);
     }
     catch (ConfigurationErrorsException e)
     {
        dialog.ShowException(e.Message + " Application shutting down.");
        **Application.Current.Shutdown();**
     }
  }

  protected override System.Windows.DependencyObject CreateShell()
  {
     var main = new MainWindow
     {
        DataContext = new MainWindowViewModel(Container.Resolve<IEventRepository>(),
                                              Container.Resolve<IDialogService>(),
                                              Container.Resolve<ISomeClass>())
     };

     return main;
  }

  protected override void InitializeShell()
  {
     base.InitializeShell();
     Application.Current.MainWindow = (Window)Shell;
     Application.Current.MainWindow.Show();
  }
}

1 个答案:

答案 0 :(得分:2)

出现这种情况,因为您此时正在执行应用程序的OnStartup。我想你这样做:

protected override void OnStartup(StartupEventArgs e)
{
    new AgentBootstrapper().Run();
}

必须在应用程序关闭之前完成OnStartup,以便引导程序继续执行。您可能会抛出另一个异常以退出Run():

 ... catch (ConfigurationErrorsException e)
 {
    dialog.ShowException(e.Message + " Application shutting down.");
    throw new ApplicationException("shutdown");
 }

然后在StartUp()中捕获它:

protected override void OnStartup(StartupEventArgs e)
{
    try
    {
        new AgentBootstrapper().Run();
    }
    catch(ApplicationException)
    {
        this.Shutdown();
    }
}
相关问题