原生WPF使用IOC容器

1、删除App.xaml中的 StartupUri=""
2、改造App.xaml.cs

 public partial class App : Application
 {
     public App()
     {
         ServiceProvider = GetServiceProvider();
     }

     private IServiceProvider GetServiceProvider()
     {
         ServiceCollection services = new ServiceCollection();
         services.AddTransient<MainView>();
         services.AddTransient<MainViewModel>();
         return services.BuildServiceProvider();
     }

     public IServiceProvider ServiceProvider { get; set; }

     protected override void OnStartup(StartupEventArgs e)
     {       
         base.OnStartup(e);
         Initialized();
        
     }
     public void Initialized()
     {
         MainView mainView = ServiceProvider.GetService<MainView>();
         mainView.Show();
     }  
 }
posted @ 2024-05-29 23:09  孤沉  阅读(83)  评论(0编辑  收藏  举报