我正在使用 Prism UnityExtensions Bootstrap 类来启动我的 WPF 应用程序。当 unityextensions Bootstrap 仍在运行时,如何关闭应用程序?
请参阅下面我的 Bootstrap 类。 SomeClass
对象可能会抛出自定义异常(致命)。如果抛出自定义异常,我需要关闭应用程序。我正在使用 Application.Current.Shutdown()
关闭应用程序。
但是, Bootstrap 代码继续运行,并且在 CreateShell()
方法中设置数据上下文时收到“ResolutionFailedException was unhandled”异常错误。显然,由于 catch block ,SomeClass
方法和接口(interface)未向容器注册。
在调用 Application.Current.Shutdown()
后, Bootstrap 代码似乎继续运行。我需要在调用 shutdown 之后立即停止 Bootstrap 代码。
有什么想法如何在不创建 ResolutionFailedException
的情况下关闭应用程序吗?
ResolutionFailedException exception details --> Resolution of the dependency failed, type = "SomeClass", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The current type, SomeClass, is an interface and cannot be constructed. Are you missing a type mapping?
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();
}
}
最佳答案
出现此行为是因为您此时正在执行应用程序的 OnStartup。我想你会这样做:
protected override void OnStartup(StartupEventArgs e)
{
new AgentBootstrapper().Run();
}
必须先完成 OnStartup,然后应用程序才能关闭,以便 Bootstrap 继续执行。您可能会抛出另一个异常来退出 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();
}
}
关于c# - 如何在 Bootstrap 类仍在运行时关闭应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9236335/