How to Implement Dependency Injection to WPF Application

  1. Add Nuget Package to the project
  2. Modify App.xaml.cs

Add the NuGet packages to the project

Add Microsoft.Extensions.DependencyInjectionMicrosoft.Extensions.Hosting

Add Microsoft.Extensions.Hosting

Modify App.xaml.cs file

  1. Create Constructor
  2. Add publist static IHost nullable
  3. Create override function for OnStartUp
  4. Create override function for OnExist
  5. Add code for Host.CreateDefaultBuilder
    • Add singleton on for MainWindow
    • Add Transient to add dependency injection for the dependency that you want to add.
 public partial class App : Application
 {
     public static IHost? AppHost { get; private set; }
     public App()
     {
         AppHost = Host.CreateDefaultBuilder()
             .ConfigureServices((services) =>
             {
                 services.AddSingleton<MainWindow>(); 
                 services.AddTransient<IGetProvinces, GetProvinces>();
             })
             .Build();
     }

     protected override async void OnStartup(StartupEventArgs e)
     {
         await AppHost!.StartAsync();

         var startupForm = AppHost.Services.GetRequiredService<MainWindow>();
         startupForm.Show();

         base.OnStartup(e);
     }

     protected override async void OnExit(ExitEventArgs e)
     {
         await AppHost!.StopAsync();
         base.OnExit(e);
     }
 }

Leave a Reply