181 lines
6.1 KiB
C#
181 lines
6.1 KiB
C#
using Avalonia;
|
||
using Avalonia.Controls;
|
||
using Avalonia.Controls.ApplicationLifetimes;
|
||
using Avalonia.Data.Core.Plugins;
|
||
using Avalonia.Markup.Xaml;
|
||
using Cowain.Base.Helpers;
|
||
using Cowain.TestProject.Services;
|
||
using Cowain.TestProject.ViewModels;
|
||
using Cowain.TestProject.Views;
|
||
using Microsoft.Extensions.Configuration;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
using Microsoft.Extensions.Hosting;
|
||
using Microsoft.Extensions.Logging;
|
||
using Serilog;
|
||
using Serilog.Events;
|
||
using System;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Threading.Tasks;
|
||
|
||
|
||
namespace Cowain.TestProject;
|
||
|
||
public partial class App : Application
|
||
{
|
||
private IHost? _host;
|
||
private IClassicDesktopStyleApplicationLifetime? _desktopLifetime;
|
||
private ILogger<App>? _logger;
|
||
public override void Initialize()
|
||
{
|
||
//StartConfig.OnStart();
|
||
AvaloniaXamlLoader.Load(this);
|
||
}
|
||
|
||
public override async void OnFrameworkInitializationCompleted()
|
||
{
|
||
if (Design.IsDesignMode)
|
||
{
|
||
base.OnFrameworkInitializationCompleted();
|
||
return;
|
||
}
|
||
|
||
try
|
||
{
|
||
_host = CreateHostBuilder().Build();
|
||
Serilog.Debugging.SelfLog.Enable(msg => File.AppendAllText("serilog-selflog.txt", msg + Environment.NewLine));
|
||
ServiceLocator.Current = _host!.Services;
|
||
_logger = _host.Services.GetRequiredService<ILogger<App>>();
|
||
_logger.LogInformation("开始应用程序初始化");
|
||
LogAndSwallowAttribute.OnExceptionAction = ex =>
|
||
{
|
||
_logger.LogError(ex, "[Fody]异常被捕获并记录");
|
||
};
|
||
AvaloniaExceptionMiddleware.Install(_logger);
|
||
await _host.StartAsync();
|
||
_host.Services.InitializePlugins();
|
||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||
{
|
||
_desktopLifetime = desktop;
|
||
DisableAvaloniaDataAnnotationValidation();
|
||
var loginWindow = CreateLoginWindow(_host.Services);
|
||
desktop.MainWindow = loginWindow;
|
||
loginWindow.Closed += async (sender, args) =>
|
||
{
|
||
if ((loginWindow.DataContext as LoginWindowViewModel)?.LoginSuccess == true)
|
||
{
|
||
ShowMainWindow(desktop, _host.Services);
|
||
}
|
||
else
|
||
{
|
||
await ShutdownApplicationAsync();
|
||
}
|
||
};
|
||
loginWindow.Show();
|
||
desktop.Exit += async (sender, args) =>
|
||
{
|
||
await ShutdownApplicationAsync();
|
||
};
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger?.LogError(ex, "应用程序初始化失败,即将退出");
|
||
Log.CloseAndFlush();
|
||
_desktopLifetime?.Shutdown(1);
|
||
}
|
||
finally
|
||
{
|
||
_logger?.LogInformation("应用程序初始化完成");
|
||
base.OnFrameworkInitializationCompleted();
|
||
}
|
||
}
|
||
|
||
private IHostBuilder CreateHostBuilder()
|
||
{
|
||
return Host.CreateDefaultBuilder()
|
||
.ConfigureAppConfiguration((hostContext, config) =>
|
||
{
|
||
config.SetBasePath(AppContext.BaseDirectory)
|
||
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
|
||
})
|
||
.ConfigureServices((hostContext, services) =>
|
||
{
|
||
services.AddServices(hostContext.Configuration, _logger);
|
||
//services.AddHostedService<InitializeDatabaseHostedService>();
|
||
//services.AddHostedService<TestHostedService>();
|
||
|
||
})
|
||
.UseSerilog((context, services, configuration) =>
|
||
{
|
||
configuration.ReadFrom.Configuration(context.Configuration)
|
||
.ReadFrom.Services(services)
|
||
.MinimumLevel.Information()
|
||
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
|
||
.ConfigureDatabaseSink(context.Configuration)
|
||
.WriteTo.File(@"Logs\Log.txt",
|
||
rollingInterval: RollingInterval.Day, // 按天的日志
|
||
shared: true, // 设置为 true,避免多个日志文件
|
||
retainedFileCountLimit: 180) // 保留最近31个文件
|
||
;
|
||
});
|
||
}
|
||
|
||
private Window CreateLoginWindow(IServiceProvider services)
|
||
{
|
||
var vm = services.GetRequiredService<LoginWindowViewModel>();
|
||
var loginWindow = new LoginWindow
|
||
{
|
||
DataContext = vm
|
||
};
|
||
|
||
return loginWindow;
|
||
}
|
||
|
||
private void ShowMainWindow(IClassicDesktopStyleApplicationLifetime desktop, IServiceProvider services)
|
||
{
|
||
var mainWindow = new MainWindow();
|
||
mainWindow.DataContext = services.GetRequiredService<MainWindowViewModel>();
|
||
mainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
|
||
mainWindow.WindowState = WindowState.Normal;
|
||
|
||
desktop.MainWindow = mainWindow;
|
||
mainWindow.Show();
|
||
|
||
_logger?.LogInformation("主窗口已显示,应用程序已启动");
|
||
}
|
||
|
||
private async Task ShutdownApplicationAsync()
|
||
{
|
||
_logger?.LogInformation("开始关闭应用程序");
|
||
try
|
||
{
|
||
if (_host != null)
|
||
{
|
||
await _host.StopAsync();
|
||
_logger?.LogInformation("后台服务已停止");
|
||
}
|
||
_host?.Services.ShutDownPlugins();
|
||
_logger?.LogInformation("插件已关闭");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger?.LogError(ex, "应用程序关闭过程中发生错误");
|
||
}
|
||
finally
|
||
{
|
||
_logger?.LogInformation("应用程序已完全关闭");
|
||
Log.CloseAndFlush();
|
||
_host?.Dispose();
|
||
_host = null;
|
||
}
|
||
}
|
||
|
||
private void DisableAvaloniaDataAnnotationValidation()
|
||
{
|
||
foreach (var plugin in BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray())
|
||
{
|
||
BindingPlugins.DataValidators.Remove(plugin);
|
||
}
|
||
}
|
||
} |