Reputation: 27
i'm getting a strange exception using MVVM Prism.
Here is my code:
LoginPageViewModel.cs file:
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Xamarin.Forms;
using Prism.Unity;
using Microsoft.Practices.Unity;
using System.Threading.Tasks;
using MobileApp.Views;
namespace MobileApp.ViewModels
{
public class LoginPageViewModel : BindableBase, INavigationAware
{
.
.
.
private INavigationService _navigationService;
public LoginPageViewModel(INavigationService navigationService, ...)
{
.
.
.
_navigationService = navigationService;
}
}
}
App.xaml.cs file where i call the LoginPage:
using Prism.Unity;
using MobileApp.Views;
using Xamarin.Forms;
using System;
using System.Globalization;
using Microsoft.Practices.Unity;
using Prism.Navigation;
using Microsoft.Practices.ServiceLocation;
using System.Diagnostics;
using MobileApp.ViewModels;
using System.Threading.Tasks;
namespace MobileApp
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer)
{
}
protected override void OnInitialized()
{
NavigationService.NavigateAsync("LoginPage"); // ERROR here (Exception)
.
.
.
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<LoginPage>();
.
.
.
}
}
}
After the NavigationService.NavigateAsync("LoginPage") call, i get this error:
System.InvalidOperationException: The current type, Prism.Navigation.INavigationService, is an interface and cannot be constructed. Are you missing a type mapping?
Does anyone know how to solve it? Thank you
Upvotes: 1
Views: 1745
Reputation: 1943
I had the same problem. I tried marking OnInitialized
as async
and used nameof
in NavigationService.NavigateAsync
to avoid typos, and it didn't work. In case somebody else had the same problem, I solved it when I added this line at the beginning of RegisterTypes
:
Container.Register<Prism.Navigation.INavigationService, Prism.Navigation.PageNavigationService>();
It registers PageNavigationService
as an implementation for INavigationService
.
Upvotes: 1
Reputation: 5799
First you might try making OnInitialized
async, await the NavigateAsync
and wrap the whole thing in a try catch with a debug output for any exception.
Second, while what you have here looks correct, this error typically occurs when the Navigation Service has a typo in the name. The way that Unity injects the Navigation Service it has to be named exactly correct or it will not resolve. You might try switching from Unity to DryIoc and see if that resolves your issue. It's also a faster DI container and actually maintained!
Upvotes: 2