You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
3.2 KiB
96 lines
3.2 KiB
using Avalonia;
|
|
using Avalonia.Controls.ApplicationLifetimes;
|
|
using Avalonia.Markup.Xaml;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using MyAvaloniaApp.Configuration;
|
|
using MyAvaloniaApp.Extensions;
|
|
using ReactiveUI;
|
|
using Splat;
|
|
using System;
|
|
using System.IO;
|
|
|
|
namespace MyAvaloniaApp;
|
|
|
|
public partial class App : Application
|
|
{
|
|
private IServiceProvider? _serviceProvider;
|
|
private ILogger<App>? _logger;
|
|
|
|
/// <summary>
|
|
/// 无参构造函数,用于 Avalonia 框架初始化
|
|
/// </summary>
|
|
public App()
|
|
{
|
|
}
|
|
|
|
public override void Initialize()
|
|
{
|
|
AvaloniaXamlLoader.Load(this);
|
|
|
|
// 注册自定义 ViewLocator
|
|
Locator.CurrentMutable.RegisterConstant(new Views.ViewLocator(), typeof(IViewLocator));
|
|
}
|
|
|
|
public override void OnFrameworkInitializationCompleted()
|
|
{
|
|
// 在框架初始化完成后创建和配置 HostBuilder
|
|
var host = CreateHostBuilder().Build();
|
|
_serviceProvider = host.Services;
|
|
_logger = _serviceProvider.GetRequiredService<ILogger<App>>();
|
|
|
|
_logger.LogInformation("App 框架初始化完成,HostBuilder 已创建并配置");
|
|
|
|
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
|
{
|
|
_logger.LogInformation("使用依赖注入创建 MainWindow");
|
|
desktop.MainWindow = _serviceProvider.GetRequiredService<MainWindow>();
|
|
}
|
|
|
|
base.OnFrameworkInitializationCompleted();
|
|
_logger.LogInformation("框架初始化完成");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 创建 HostBuilder
|
|
/// </summary>
|
|
/// <returns>HostBuilder</returns>
|
|
private IHostBuilder CreateHostBuilder() =>
|
|
Host.CreateDefaultBuilder()
|
|
.ConfigureAppConfiguration((context, config) =>
|
|
{
|
|
// 配置应用程序设置
|
|
config.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
|
|
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true)
|
|
.AddEnvironmentVariables();
|
|
})
|
|
.ConfigureLogging((context, logging) =>
|
|
{
|
|
// 配置日志
|
|
logging.ClearProviders();
|
|
logging.AddConfiguration(context.Configuration.GetSection("Logging"));
|
|
// 启用控制台日志以便调试
|
|
logging.AddConsole();
|
|
logging.AddDebug();
|
|
})
|
|
.ConfigureServices((context, services) =>
|
|
{
|
|
// 注册配置
|
|
services.Configure<AppSettings>(context.Configuration.GetSection("AppSettings"));
|
|
|
|
// 注册业务服务
|
|
services.AddBusinessServices();
|
|
|
|
// 注册 ViewModel
|
|
services.AddViewModels();
|
|
|
|
// 注册 ReactiveUI 服务
|
|
services.AddReactiveUI();
|
|
|
|
// 注册 Avalonia 应用程序
|
|
services.AddTransient<MainWindow>();
|
|
});
|
|
}
|