如何在引导程序类仍在运行时关闭应用程序?
问题描述:
我正在使用Prism UnityExtensions引导程序类来启动我的WPF应用程序。 unityextensions引导程序仍在运行时如何关闭应用程序?如何在引导程序类仍在运行时关闭应用程序?
请参阅下面的我的引导程序类。 SomeClass
对象可能会引发自定义异常(致命)。如果自定义异常被抛出,我需要关闭应用程序。我正在使用Application.Current.Shutdown()
来关闭应用程序。
但是,引导程序代码继续运行,并且在CreateShell()
方法中设置datacontext时,出现“ResolutionFailedException was unhandled”异常错误。显然,由于catch块,SomeClass
方法和接口未在容器中注册。
在呼叫Application.Current.Shutdown()
的调用被调用后,看起来引导程序代码继续运行。我需要在关闭调用之后立即停止引导程序代码。
任何想法如何关闭应用程序而不创建ResolutionFailedException
?
ResolutionFailedException异常的详细信息 - > 分辨率依赖的失败,TYPE = “SomeClass的”,名字= “(无)”。 发生异常时:解析时。 异常是: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();
}
}
答
出现此现象,因为you're此时执行应用程序的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");
}
然后抓住它在启动():
protected override void OnStartup(StartupEventArgs e)
{
try
{
new AgentBootstrapper().Run();
}
catch(ApplicationException)
{
this.Shutdown();
}
}
你猜对了!我从OnStartup方法运行引导程序。我没有意识到OnStartup方法必须在应用程序关闭之前完成运行。我按照你的例子改变了我的代码,它效果很好。非常感谢您的帮助。 – EnLaCucha 2012-02-13 16:38:34