Unregister view-Viewmodel Prism xamarin dryioc

262 Views Asked by At

I have a situation where I need to Unregister a ViewModel and rerregister it .

The reason is that at times I want to inject a "fakeservice" rather than the "real one".

So if I press the "offline" button I need to unregister the viewModels and re-register them so that the Fakeservices are used.

How can i unregister a view-viewmodel using prism and dryioc

I usuall Register like this:

  protected override void RegisterTypes(Prism.Ioc.IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation<MyPage,MyPageViewModel>();
}

How do I unregister the above?

thanks

2

There are 2 best solutions below

4
On BEST ANSWER

When you register your View and ViewModel with that extension, it is worth noting that the ViewModel itself is not registered with the container, it is only registered with the ViewModelLocationProvider which provides the ViewModel type to resolve for a given View.

It is also worth noting here that ViewModels are resolved with a Transient Lifetime which means that each time it is resolved you get a new instance, so all you would really need to do is Navigate away and then back again.

2
On

The reason is that at times I want to inject a "fakeservice" rather than the "real one".

No need to unregister the view model. The service is injected when the instance is created.

But you should not use the container for this anyway - create a service provider instead, then you can switch that one to the currently active service. That's even possible transparently for the consumer if the service provider implements the service interface itself.

public interface IService
{
    void DoStuff();
}

public interface IServiceProvider
{
    void SetActiveService( Type serviceType );
}

internal ServiceProvider : IServiceProvider, IService
{
    void IService.DoStuff() => _currentService.DoStuff();

    public void SetActiveService( Type serviceType )
    {
        _currentService = _container.Resolve( serviceType );
    }

    private IService _currentService;
}

Add some synchronization and error handling and refactor away the container reference for production, though.

With Unity I'd register the provider as unnamed standard implementation and register all actual services as named implementations and have an IEnumerable<Func<IService>> injected into the service provider. Perhaps DryIoc offers similar functionality.