.NET Core Dependency Injection for WPF Core

Short story about Dependency Injection

Why use Dependency Injection

Also, another cool feature is the locating of the right classes. There is no more passing of objects in constructors. You just define in the constructor of a class on which interfaces it depends and dependency injection will handle it for you.

For more information and explanation about this subject check out this great article by Halil İbrahim Kalkan.

Configure Dependency Injection in WPF .Core

Next, install these NuGet Packages.

Configuring the OnStartUp method

Next, add these using statements and add these two fields to the App.xaml.cs class.

Now we gone to add the OnStartUp method. In my example, I also use an appsettings file.

If you aren’t going to use the appsettings file, you can remove line 18 and line 22 till line 26.

Next, add the method ConfigureServices.

The last step is to remove the StartupUri in App.xaml. In the example below its on line 5.

Explanation of the code

Next, we created a service collection and we pass this to the ConfigureServices method. In the ConfigureServices method, we register the dependencies. For now, I only register the MainWindow class.

In the last lines, we create a Service Provider with the service collection and assign it to the field ServiceProvider. Then we request an object of type MainWindow from the ServiceProvider and call the method Show to display the UI.

Wrapping up

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store