ChineseChess/ChineseChess.GUI/App.xaml.cs
2021-05-30 22:57:53 +08:00

97 lines
3.3 KiB
C#

using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using ChineseChess.GUI.Contracts.Services;
using ChineseChess.GUI.Contracts.Views;
using ChineseChess.GUI.Core.Contracts.Services;
using ChineseChess.GUI.Core.Services;
using ChineseChess.GUI.Models;
using ChineseChess.GUI.Services;
using ChineseChess.GUI.ViewModels;
using ChineseChess.GUI.Views;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace ChineseChess.GUI
{
public partial class App : Application
{
private IHost _host;
public T GetService<T>()
where T : class
=> _host.Services.GetService(typeof(T)) as T;
public App()
{
}
private async void OnStartup(object sender, StartupEventArgs e)
{
var appLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
// For more information about .NET generic host see https://docs.microsoft.com/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0
_host = Host.CreateDefaultBuilder(e.Args)
.ConfigureAppConfiguration(c =>
{
c.SetBasePath(appLocation);
})
.ConfigureServices(ConfigureServices)
.Build();
await _host.StartAsync();
}
private void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
// TODO WTS: Register your services, viewmodels and pages here
// App Host
services.AddHostedService<ApplicationHostService>();
// Activation Handlers
// Core Services
services.AddSingleton<IFileService, FileService>();
// Services
services.AddSingleton<IApplicationInfoService, ApplicationInfoService>();
services.AddSingleton<ISystemService, SystemService>();
services.AddSingleton<IPersistAndRestoreService, PersistAndRestoreService>();
services.AddSingleton<IThemeSelectorService, ThemeSelectorService>();
services.AddSingleton<IPageService, PageService>();
services.AddSingleton<INavigationService, NavigationService>();
// Views and ViewModels
services.AddTransient<IShellWindow, ShellWindow>();
services.AddTransient<ShellViewModel>();
services.AddTransient<MainViewModel>();
services.AddTransient<MainPage>();
services.AddTransient<SettingsViewModel>();
services.AddTransient<SettingsPage>();
// Configuration
services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
}
private async void OnExit(object sender, ExitEventArgs e)
{
await _host.StopAsync();
_host.Dispose();
_host = null;
}
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
// TODO WTS: Please log and handle the exception as appropriate to your scenario
// For more info see https://docs.microsoft.com/dotnet/api/system.windows.application.dispatcherunhandledexception?view=netcore-3.0
}
}
}