Files
XplorePlane/XplorePlane/App.xaml.cs
T
zhengxuan.zhang 029752e231 #0005 增加日志
2026-03-13 16:59:31 +08:00

93 lines
2.9 KiB
C#

using System;
using System.Windows;
using XplorePlane.Views;
using XplorePlane.ViewModels;
using XplorePlane.Services;
using Prism.Ioc;
using Prism.DryIoc;
using Serilog;
namespace XplorePlane
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// 配置 Serilog 日志系统
SerilogConfig.Configure();
// 捕获未处理的异常
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
DispatcherUnhandledException += OnDispatcherUnhandledException;
base.OnStartup(e);
// Initialize Prism with DryIoc
var bootstrapper = new AppBootstrapper();
bootstrapper.Run();
}
protected override void OnExit(ExitEventArgs e)
{
// 关闭并刷新日志
SerilogConfig.CloseAndFlush();
base.OnExit(e);
}
/// <summary>
/// 处理未捕获的异常
/// </summary>
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
Log.Fatal(exception, "应用程序发生未处理的异常");
MessageBox.Show(
$"应用程序发生严重错误:\n\n{exception?.Message}\n\n请查看日志文件获取详细信息。",
"严重错误",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
/// <summary>
/// 处理 UI 线程未捕获的异常
/// </summary>
private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "UI 线程发生未处理的异常");
MessageBox.Show(
$"应用程序发生错误:\n\n{e.Exception.Message}\n\n请查看日志文件获取详细信息。",
"错误",
MessageBoxButton.OK,
MessageBoxImage.Error);
// 标记为已处理,防止应用程序崩溃
e.Handled = true;
}
}
public class AppBootstrapper : PrismBootstrapper
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// 注册日志服务
containerRegistry.RegisterSingleton<ILoggerService, LoggerService>();
// 注册视图和视图模型
containerRegistry.RegisterForNavigation<MainWindow>();
containerRegistry.Register<MainViewModel>();
Log.Information("依赖注入容器配置完成");
}
}
}