How to .NET Core 3.0 Wpf application use Dependency Injection

I have recently come across this requirement to a project I am working on that requires Dependency Injection.

For this we need to install/add nuget package to our Wpf project:

Microsoft.Extensions.DependencyInjection

In my case I created a class that I want to use for logging called it LogBase, so in my App.xaml.cs class add following, this is a basic example:

private readonly ServiceProvider _serviceProvider;

public App()
{
    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection);
    _serviceProvider = serviceCollection.BuildServiceProvider();
}

private void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ILogBase>(new LogBase(new FileInfo($@"C:\temp\log.txt")));
    services.AddSingleton<MainWindow>();
}

private void OnStartup(object sender, StartupEventArgs e)
{
    var mainWindow = _serviceProvider.GetService<MainWindow>();
    mainWindow.Show();
}

In your App.xaml, add Startup=”OnStartup” so it looks like this:

<Application x:Class="VaultDataStore.Wpf.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:VaultDataStore.Wpf"
             Startup="OnStartup">
    <Application.Resources>

    </Application.Resources>
</Application>

So in you MainWindow.xaml.cs you inject ILogBase in constructor like this:

private readonly ILogBase _log;

public MainWindow(ILogBase log)
{
    _log = log;

    ...etc.. you can use _log over all in this class

in my LogBase class I use any logger I like in my way.

I have added all this together in github repo.

Leave a Reply