Skip to content

Instantly share code, notes, and snippets.

@AliveDevil
Created October 14, 2023 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AliveDevil/3bd65d7f5629e8c82255be2126282684 to your computer and use it in GitHub Desktop.
Save AliveDevil/3bd65d7f5629e8c82255be2126282684 to your computer and use it in GitHub Desktop.
AvaloniaUI Microsoft.Extensions.Hosting interop
using Avalonia;
using Avalonia.Threading;
using Avalonia.ReactiveUI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ReactiveUI;
using Splat;
using Splat.Microsoft.Extensions.DependencyInjection;
using System;
namespace app;
static class Program
{
[STAThread]
public static void Main(string[] args)
=> BuildAvaloniaApp()
.UseMicrosoftExtensionsHosting(args)
.StartWithClassicDesktopLifetime(args);
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.UseReactiveUI()
.WithInterFont()
.LogToTrace();
private static void ConfigureServices(IServiceCollection services)
{
// Configure your IHost-services here.
}
private static void OnSetup(this HostApplicationBuilder applicationBuilder, AppBuilder appBuilder)
{
var dispatcher = Dispatcher.UIThread;
var app = appBuilder.Instance!;
applicationBuilder.Services
.AddSingleton(app)
.AddSingleton(app.ApplicationLifetime!)
.AddSingleton(app.PlatformSettings!)
.AddSingleton(dispatcher);
var host = applicationBuilder.Build();
host.Services.UseMicrosoftDependencyResolver();
dispatcher.ShutdownStarted += host.Shutdown;
dispatcher.Post(static arg =>
{
var host = (IHost)arg!;
host.StartAsync()
.GetAwaiter()
.GetResult();
}, host, DispatcherPriority.Send);
}
private static AppBuilder UseMicrosoftExtensionsHosting(this AppBuilder builder, string[] args)
{
var hostBuilder = Host.CreateApplicationBuilder(args);
hostBuilder.Services.UseMicrosoftDependencyResolver();
Locator.CurrentMutable.InitializeSplat();
Locator.CurrentMutable.InitializeReactiveUI();
ConfigureServices(hostBuilder.Services);
builder.AfterSetup(hostBuilder.OnSetup);
return builder;
}
private static void Shutdown(this IHost host, object? sender, EventArgs e)
=> host.StopAsync().GetAwaiter().GetResult();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment