Using DI with ViewModel classes
All of the popular MVVM frameworks include a DI container to manage dependencies. Because we are handing MVVM ourselves, we will use a DI container that isn't bundled with any MVVM framework. Microsoft has included its own DI container in ASP.NET Core that is lightweight and easy to use. Luckily, this container is also available to other types of .NET projects, via a NuGet package.
In the MyMediaCollection
project, open NuGet Package Manager and search for Microsoft.Extensions.DependencyInjection
:
Select the package and install the latest available version. After the installation completes, close the NuGet Package Manager tab and open App.xaml.cs
. We have to make a few changes here to start using the DI container.
Microsoft implements a DI container through a class called ServiceCollection
. As the name implies, it is intended to create a collection of services for...