Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Hosting
現在我門來該造App裡面的程式碼
1 public partial class App : Application 2 { 3 private static IHost? host; 4 private IHost CreateHost() 5 => Host.CreateDefaultBuilder(Environment.GetCommandLineArgs()) 6 .ConfigureServices(RegisterService) 7 .Build(); 8 public override void Initialize() 9 { 10 AvaloniaXamlLoader.Load(this); 11 } 12 public override void OnFrameworkInitializationCompleted() 13 { 14 host = CreateHost(); 15 if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) 16 { 17 desktop.MainWindow = GetService<MainWindow>(); 18 } 19 base.OnFrameworkInitializationCompleted(); 20 _ = host.StartAsync(); 21 } 22 public static T? GetService<T>() 23 { 24 if (host is null) return default; 25 return host.Services.GetService<T>(); 26 } 27 protected virtual void RegisterService(IServiceCollection services) 28 { 29 services.AddSingleton<MainWindow>(); 30 services.AddSingleton<MainWindowViewModel>(); 31 } 32 }
這樣就可以使用微軟的DI服務了