Application Lifetimes
Not all platforms are created equal! For example, the lifetime management that you may be used to developing with in Windows Forms or WPF can operate only on desktop-style platforms. Avalonia UI is a cross-platform framework; so to make your application portable, it provides several different lifetime models for your application, and also allows you to control everything manually if the target platform permits.
How do lifetimes work?
For a desktop application, you initialise like this:
class Program
{
// This method is needed for IDE previewer infrastructure
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>().UsePlatformDetect();
// The entry point. Things aren't ready yet, so at this point
// you shouldn't use any Avalonia types or anything that expects
// a SynchronizationContext to be ready
public static int Main(string[] args)
=> BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
Then the main window is created in the Application
class:
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime
is IClassicDesktopStyleApplicationLifetime desktop)
desktop.MainWindow = new MainWindow();
else if (ApplicationLifetime
is ISingleViewApplicationLifetime singleView)
singleView.MainView = new MainView();
base.OnFrameworkInitializationCompleted();
}
This method is called when the framework has initialized and the ApplicationLifetime
property contains the chosen lifetime if any.
If you run the application in design mode (this uses the IDE previewer process), then ApplicationLifetime
is null.
Lifetime Interfaces
Avalonia UI provides a range of interfaces to allow you to choose a level of control that is suitable for your application. These are provided by the BuildAvaloniaApp().Start[Something]
family of methods.