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:


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();
    _serviceProvider = serviceCollection.BuildServiceProvider();

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

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

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

<Application x:Class="VaultDataStore.Wpf.App"


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 Comment