2

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

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

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

在调用调用后,引导程序代码似乎继续运行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();
  }
}
4

1 回答 1

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();
    }
}
于 2012-02-11T10:18:30.177 回答