Avalonia如何与通用主机Host集成实现MsDI
如果想在Aavalonia使用IOC,目前我能想到的就是使用Prism或者是MsDI,Prism内部使用的是DryIoc,这个和WPF几乎没什么差别,那如果我想使用微软实现的Ioc呢,也是可以的,实现方式其实很简单,就是使用IHost,其中依赖有两个库
View Code
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服务了