I have a situation where I want to switch between "FakeService" and "RealService" at runtime.
MyViewModel
public class BookingViewModel
{
private readonly IBookingService bookingService;
public WelcomePageViewModel(
INavigationService navigationService,IBookingService bookingService)
{
this.bookingService= bookingService;
}
}
In my App.xaml I do as follows:
private IContainer container;
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
container = containerRegistry.GetContainer();
RegisterRealServices()
}
private void RegisterRealServices()
{
container.Register<IBookingService, RealBookingService>(Reuse.Singleton);
}
user presses a menu option to use fake services now.So Unregister the real ones and use the fake one.
However what I have done below does not seem to work because I keep getting redirected to the "RealBookingService" and not to the "FakeBookingService"
How can I do it?
private void RegisterFakeServices()
{
container.Unregister<IBookingService>();
container.Register<IBookingService,FakeBookingService>(
Reuse.Singleton,
ifAlreadyRegistered: IfAlreadyRegistered.Replace);
}
Question: Is it possible to switch service implementation at runtime? How do you do it using DryIoc?
I am not an expert in Xamarin, but un(re)registering in DryIoc requires a special preparation (specifically for singleton). That's because service creation may be already cached.
Here is the wiki explaining this in detail: https://bitbucket.org/dadhi/dryioc/wiki/UnregisterAndResolutionCache