Search code examples
xamarin.formsunity-containerprism

Unregister View and ViewModel in Prism.Unity.Forms


I am using Prism with Unity container for my Xamarin Forms application.

where I am registering my pages like this

Container.RegisterTypeForNavigation<ViewType,ViewModelType>();

sometimes

Container.RegisterTypeForNavigation<ViewType>();

Now I want to Unregister some of the registered pages along with their ViewModel.

Something like

Container.UnRegisterTypeForNavigation<ViewType>();

But can't figure out a way for it. need help.

So far I have tried this,

ContainerRegistration registrationContainer = Container.Registrations.FirstOrDefault(obj => obj.MappedToType == GetPageType(pageType));
if (registrationContainer?.LifetimeManager!=null)
{
    registrationContainer.LifetimeManager.RemoveValue();
}

with no luck.

Reason why I want to Unregister...

I have two views

Project.Namespace1.ViewA
Project.Namespace2.ViewA

Now I want to open Project.Namespace1.ViewA is some cases, and Project.Namespace2.ViewA in other cases.

This can be done as

NavigationService.NavigateAsync("ViewA");

It navigates to last view registered in Unity container. That's why I want to unregister previous view before registering new view.


Solution

  • You should navigate to Project.Namespace1.ViewA and Project.Namespace2.ViewA (or some other unique names).

    RegisterTypeForNavigation takes an optional string argument for the name, so pass an unique name for each of your views. When navigating to ViewA you should then navigate to the concrete ViewA you want to navigate to. If you absolutely need to emulate the register-unregister-behavior, create a service that holds the currently active ViewA.

    Example:

    Container.RegisterTypeForNavigation<Project.Namespace1.ViewA,ViewModelType>( "ViewA1" );
    Container.RegisterTypeForNavigation<Project.Namespace2.ViewA,ViewModelType>( "ViewA2" );
    
    interface IViewASelector
    {
        string ViewA { get; set; }
    }
    
    // register Namespace1 and unregister Namespace2
    _viewASelector.ViewA ="ViewA1";
    
    // navigate to the active ViewA
    NavigationService.NavigateAsync( _viewASelector.ViewA );
    

    Probably, you also want an enum instead of a bunch of strings.