dependenciesmauicode-injection

.NET MAUI 8: System.Reflection.TargetInvocationException on initializing the main view with dependency injection


There has never been any problem with the following code:

public partial class SelectionPage : ContentPage
{
    private SelectionViewModel vm;

    public SelectionPage(SelectionViewModel viewmodel)
    {
       InitializeComponent();
       this.vm = viewmodel;
       BindingContext = viewmodel;
       viewmodel.PropertyChanged += Viewmodel_PropertyChanged;
    }

But when I install it on a new device, or on a new Simulator I get the following error: System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

I found a strange workaround which allows me to continue development for the moment: If I comment out the line: // BindingContext = viewmodel; I can deploy the app on my device. Once it has been successfully deployed I can reactivate BindingContext = viewmodel; and it works.

Of course I have to find the cause of this bug in order to make my app available to my testers. I am grateful for all tips.


Solution

  • It is good practice to have a look at the inner exception. Thank you @Jason for that tip. A TargetInvocationException may pop up during initialization with dependency injection whenever there is a previous unhandled exception. In my case this unhandled exception was thrown only on first time installation, for example on a new device or a new emulator.