Short story about Dependency Injection
With .NET Core, the Microsoft team added a build support for dependency injection. Prior to .NET Core, there wasn’t a built-in support. There where a lot of third-party libraries like Autofac that supported dependency injection.
Why use Dependency Injection
I’m not going to go very deep in the subject. There are a lot of articles that describe the how, why, pros and cons. But in short, the great benefit of dependency injection is loose coupling. Classes only depend on classes implementing a particular interface.
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
First, start by creating a WPF Core project if you haven't done so before. I’m using Visual Studio 2019. You must use the .NET Core template project and not the .NET Framework project.
Next, install these NuGet Packages.
Configuring the OnStartUp method
Go to the App.xaml.cs file in your project.
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
A short explanation of the StartUp method. First, we create a ConfigurationBuilder. We use this for building a Configuration object. Dotnet Core supports the handling of reading and passing of the configuration to classes.
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.
This article was a brief explanation on how to configure dependency injection for WPF Core. With ASP Core projects its default configured from by the Visual Studio template. If you would like to see more of the code. Check out my git repo.