Dependency Injection in WPF Application using Generic HostBuilder

Creating Generic HostBuilder

Nuget :

PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.2

The HostBuilder class is available from the following namespace,

using Microsoft.Extensions.Hosting;

Initialize the Host

Within Constructor of App class(file: App.xaml.cs) please add below code to build Host,

host = new HostBuilder()
           .ConfigureServices((hostContext, services) =>
           {
 
           }).Build();

DI Container

host = new HostBuilder()
          .ConfigureServices((hostContext, services) =>
          {
              //Add business services as needed
              services.AddScoped<IEmployeeViewModel, EmployeeViewModel>();
 
              //Lets Create single tone instance of Master windows
              services.AddSingleton<EmployeeWindow>();
 
          }).Build();

Setting up OnStartup and OnExit Application events

private void OnStartup(object sender, StartupEventArgs e)
        {
            var mainWindow = host.Services.GetService<EmployeeWindow>();
            mainWindow.Show();
        }
protected override async void OnExit(ExitEventArgs e)
       {
           using (host)
           {
               await host.StopAsync();
           }
 
           base.OnExit(e);
       }

App.XAML file used as below,

<Application x:Class="WPFDesktopApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Startup="OnStartup">
    <Application.Resources>
         
    </Application.Resources>
</Application>

References
https://www.thecodebuzz.com/dependency-injection-wpf-generic-hostbuilder-net-core/
https://laurentkempe.com/2019/09/03/WPF-and-dotnet-Generic-Host-with-dotnet-Core-3-0/