As we mentioned in our tutorial on setting up your project using a MVVM software engineering pattern, you will use a ViewModel to put your business logic into and bind that to the code behind of your view. The above example doesn’t instantiate a new ViewModel object. As you can see the ViewModel is provided in the constructor of the code behind. This is because the ViewModel is being injected by the .NET MAUI framework.
How to Setup your .NET MAUI Project to use Dependency Injection
With the above example we have to configure the framework so that is knows how to inject our HomeViewModel. To do so go to your MauiProgram.cs file.
In the above MauiProgram.cs file in order to use dependency injection for a VIewModel we have to register our View and our ViewModel as Singletons as shown above.
Once you register your ViewModel and View as a Singleton you can inject your ViewModel into the code behind’s constructor!
You can also register other classes that you want to inject in the MauiProgram.cs file and you can inject those into the constructors of other classes. A good example of what else you might want to register and inject is your database access object class. You would likely want to inject the database access object class into your ViewModel’s constructor.
Best practice for unit testing is to use an interface with your objects that you want injected and inject the interface instead
If you want to do unit testing you will make your life easier by taking the objects you want to inject and creating an interface for those objects and inject the interface instead.
In the above image we are defining our dependency injection in MauiProgram.cs. Note that for our data access objects when we add them as a singleton for dependency injection we first define the interface for the object, then the object itself.
You would then inject the interface for the object directly into the constructor of the object you need the injection in. In the example image below we are injecting the interfaces for StudentDataAccess and ClassDataAccess into the constructor of our HomePageViewModel class.
If you use the interface for the object rather than the object itself when you want to do unit testing you can choose a different class that supplies test data with the interface instead and you only have to update your MauiProgram.cs file with the different interface, class dependency injection coupling in order to supply test data.
Leave a Reply