|
| 1 | +using Avalonia; |
| 2 | +using Avalonia.Controls; |
| 3 | +using Avalonia.Controls.ApplicationLifetimes; |
| 4 | +using Avalonia.Threading; |
| 5 | +using Lifter.Core; |
| 6 | +using Microsoft.Extensions.Configuration; |
| 7 | +using Microsoft.Extensions.DependencyInjection; |
| 8 | +using Microsoft.Extensions.Hosting; |
| 9 | + |
| 10 | +namespace Lifter.Avalonia; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// An abstract base class for creating a hosted Avalonia application with |
| 14 | +/// dependency injection, configuration, and IHostedService support. |
| 15 | +/// </summary> |
| 16 | +/// <typeparam name="TMainView"> |
| 17 | +/// The main view type. Must be a Control and implement <see cref="IHostedView"/>. |
| 18 | +/// </typeparam> |
| 19 | +public abstract class HostedApplication<TMainView> : global::Avalonia.Application |
| 20 | + where TMainView : Control, IHostedView |
| 21 | +{ |
| 22 | + /// <summary> |
| 23 | + /// The host application builder used to configure services and configuration. |
| 24 | + /// </summary> |
| 25 | + protected readonly HostApplicationBuilder _hostApplicationBuilder; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Gets the application's configured services. |
| 29 | + /// </summary> |
| 30 | + /// <exception cref="InvalidOperationException">Thrown if the application host has not been built yet.</exception> |
| 31 | + public IServiceProvider Services => Host?.Services |
| 32 | + ?? throw new InvalidOperationException("The application host has not been built yet."); |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Gets the application's configuration. |
| 36 | + /// </summary> |
| 37 | + public IConfiguration Configuration => _hostApplicationBuilder.Configuration; |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// Gets the configured application host. |
| 41 | + /// </summary> |
| 42 | + public IHost? Host { get; private set; } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Initializes a new instance of the <see cref="HostedApplication{TMainView}"/> class. |
| 46 | + /// </summary> |
| 47 | + protected HostedApplication() |
| 48 | + { |
| 49 | + _hostApplicationBuilder = Microsoft.Extensions.Hosting.Host.CreateApplicationBuilder(); |
| 50 | + } |
| 51 | + |
| 52 | + /// <inheritdoc/> |
| 53 | + public sealed override void OnFrameworkInitializationCompleted() |
| 54 | + { |
| 55 | + // Show splash screen if provided (optional) |
| 56 | + Window? splashWindow = null; |
| 57 | + var splashScreenContent = CreateSplashScreen(); |
| 58 | + |
| 59 | + if (splashScreenContent != null) |
| 60 | + { |
| 61 | + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) |
| 62 | + { |
| 63 | + splashWindow = new Window |
| 64 | + { |
| 65 | + Content = splashScreenContent, |
| 66 | + WindowStartupLocation = WindowStartupLocation.CenterScreen, |
| 67 | + SystemDecorations = SystemDecorations.None, |
| 68 | + SizeToContent = SizeToContent.WidthAndHeight, |
| 69 | + Title = "Loading..." |
| 70 | + }; |
| 71 | + desktop.MainWindow = splashWindow; |
| 72 | + } |
| 73 | + else if (ApplicationLifetime is ISingleViewApplicationLifetime singleView) |
| 74 | + { |
| 75 | + singleView.MainView = splashScreenContent; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + // Build the host |
| 80 | + Host = BuildHostInternal(); |
| 81 | + |
| 82 | + // Start initialization on background thread |
| 83 | + _ = Task.Run(async () => |
| 84 | + { |
| 85 | + try |
| 86 | + { |
| 87 | + // Allow derived classes to perform custom initialization |
| 88 | + await OnHostInitializedAsync(); |
| 89 | + |
| 90 | + // Switch to UI thread for view setup |
| 91 | + await Dispatcher.UIThread.InvokeAsync(() => |
| 92 | + { |
| 93 | + SetupMainView(splashWindow); |
| 94 | + }); |
| 95 | + |
| 96 | + // Start hosted services |
| 97 | + HostManager.Initialize(Services); |
| 98 | + await HostManager.StartAsync(); |
| 99 | + } |
| 100 | + catch (Exception ex) |
| 101 | + { |
| 102 | + // Log or handle startup errors |
| 103 | + Console.WriteLine($"Application startup failed: {ex}"); |
| 104 | + throw; |
| 105 | + } |
| 106 | + }); |
| 107 | + |
| 108 | + base.OnFrameworkInitializationCompleted(); |
| 109 | + } |
| 110 | + |
| 111 | + /// <summary> |
| 112 | + /// Builds and configures the application host. |
| 113 | + /// </summary> |
| 114 | + private IHost BuildHostInternal() |
| 115 | + { |
| 116 | + // Register the main view as a singleton |
| 117 | + _hostApplicationBuilder.Services.AddSingleton<TMainView>(); |
| 118 | + |
| 119 | + // Allow derived classes to register services |
| 120 | + ConfigureServices(_hostApplicationBuilder.Services, _hostApplicationBuilder.Configuration); |
| 121 | + |
| 122 | + return _hostApplicationBuilder.Build(); |
| 123 | + } |
| 124 | + |
| 125 | + /// <summary> |
| 126 | + /// Sets up the main view for Desktop or Mobile platforms. |
| 127 | + /// </summary> |
| 128 | + /// <param name="splashWindow">The splash window to close after setup (Desktop only).</param> |
| 129 | + private void SetupMainView(Window? splashWindow) |
| 130 | + { |
| 131 | + var mainView = Services.GetRequiredService<TMainView>(); |
| 132 | + |
| 133 | + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) |
| 134 | + { |
| 135 | + // Desktop: Create a Window with the view as content |
| 136 | + var windowConfig = Services.GetService<WindowConfiguration>() ?? new WindowConfiguration(); |
| 137 | + |
| 138 | + var mainWindow = new Window |
| 139 | + { |
| 140 | + Title = windowConfig.Title, |
| 141 | + Content = mainView, |
| 142 | + Width = windowConfig.Width, |
| 143 | + Height = windowConfig.Height, |
| 144 | + WindowState = windowConfig.WindowState, |
| 145 | + WindowStartupLocation = windowConfig.StartupLocation |
| 146 | + }; |
| 147 | + |
| 148 | +#if DEBUG |
| 149 | + // Enable DevTools in debug mode |
| 150 | + mainWindow.AttachDevTools(); |
| 151 | +#endif |
| 152 | + |
| 153 | + desktop.MainWindow = mainWindow; |
| 154 | + mainWindow.Show(); |
| 155 | + |
| 156 | + // Close splash screen |
| 157 | + splashWindow?.Close(); |
| 158 | + } |
| 159 | + else if (ApplicationLifetime is ISingleViewApplicationLifetime singleView) |
| 160 | + { |
| 161 | + // Mobile: Set the view directly |
| 162 | + singleView.MainView = mainView; |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + /// <summary> |
| 167 | + /// Creates the splash screen control to be displayed during initialization. |
| 168 | + /// </summary> |
| 169 | + /// <returns>The splash screen control, or null if no splash screen should be shown.</returns> |
| 170 | + /// <remarks> |
| 171 | + /// Override this method in derived classes to provide a custom splash screen. |
| 172 | + /// The splash screen will be shown while the application is initializing. |
| 173 | + /// </remarks> |
| 174 | + protected virtual Control? CreateSplashScreen() |
| 175 | + { |
| 176 | + return null; // No splash screen by default |
| 177 | + } |
| 178 | + |
| 179 | + /// <summary> |
| 180 | + /// Called when the host has completed its initialization process asynchronously. |
| 181 | + /// </summary> |
| 182 | + /// <returns>A task representing the asynchronous operation.</returns> |
| 183 | + /// <remarks> |
| 184 | + /// Override this method to perform custom initialization tasks after the host is built |
| 185 | + /// but before the main view is displayed. This runs on a background thread. |
| 186 | + /// </remarks> |
| 187 | + protected virtual Task OnHostInitializedAsync() |
| 188 | + { |
| 189 | + return Task.CompletedTask; |
| 190 | + } |
| 191 | + |
| 192 | + /// <summary> |
| 193 | + /// Configures application services and registers them with the dependency injection container. |
| 194 | + /// </summary> |
| 195 | + /// <param name="services">The <see cref="IServiceCollection"/> to which services are added.</param> |
| 196 | + /// <param name="configuration">The <see cref="IConfiguration"/> instance containing application configuration settings.</param> |
| 197 | + /// <remarks> |
| 198 | + /// This method is called during application startup to configure services. |
| 199 | + /// Use this method to register your application's services, background services, and dependencies. |
| 200 | + /// </remarks> |
| 201 | + protected abstract void ConfigureServices(IServiceCollection services, IConfiguration configuration); |
| 202 | +} |
0 commit comments