I am building my first Xamarin mobile application (android / iOS) with PRISM. I'm following this very helpful tutorial https://xamgirl.com/prism-in-xamarin-forms-step-by-step-part-1/
Problem is the IUnityContainer that gets injected into my ViewModels does not have the types that I registered in the PrismApplication's RegisterTypes(IContainerRegistry containerRegistry) function.
My question is:
How do I register my types into the IUnityContainer so that I can resolve them within my ViewModel?
OR
How do I get the Container that does have the types that I registered?
public partial class App : PrismApplication
{
public App(IPlatformInitializer Initializer) : base (Initializer) { }
protected override async void OnInitialized()
{
InitializeComponent();
MainPage = this.Container.Resolve<MainPage>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
//I have read that these registrations should not be necessary, however it crashes if I remove them because I inject them into some view models
containerRegistry.Register<INavigationService, Prism.Navigation.PageNavigationService>();
containerRegistry.Register<IPageDialogService, Prism.Services.PageDialogService>();
containerRegistry.Register<IEventAggregator, Prism.Events.EventAggregator>();
containerRegistry.Register<IUnityContainer, UnityContainer>();
//Pages
containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
containerRegistry.RegisterForNavigation<AboutPage, AboutViewModel>();
containerRegistry.RegisterForNavigation<ItemDetailPage, ItemDetailViewModel>();
containerRegistry.RegisterForNavigation<ItemsPage, ItemsViewModel>();
containerRegistry.RegisterForNavigation<NewItemPage, NewItemViewModel>();
}
}
public partial class MainPage : MasterDetailPage
{
public MainPageViewModel Model
{
get { return BindingContext as MainPageViewModel; }
set { BindingContext = value; }
}
private IUnityContainer _Container;
public MainPage(IUnityContainer container, ItemsPage detail, MainPageViewModel model)
{
InitializeComponent();
MasterBehavior = MasterBehavior.Popover;
Model = model;
Detail = detail;
_Container = container; // I cannot use this container to resolve any of my registered types ???
// for example, _Container cannot be used to resolve a <ItemsPage>
}
}
First thing is that you do not need to pass IUnityContainer as dependency parameter and manually resolve it, you can directly pass the required services as parameters it will be automatically resolved by the framework.
Second, you should be passing dependencies in your ViewModel and not the view as all the logic supposed to be written in ViewModel.
private INavigationService _navigationService;
private IPageDialogService _dialogService;
public MainPageViewModel(INavigationService navigationService, IPageDialogService dialogService)
{
_navigationService = navigationService;
_dialogService = dialogService;
}
These services will be resolved by framework and ready to use in your ViewModel.