I'm using MvvmCross
to develop my Android app. In that I want to have a Singleton instance of particular ViewModel
. For that I tried to implement in similar way as mentioned on this link
Following is my code in my App.cs
public class App : Cirrious.MvvmCross.ViewModels.MvxApplication
{
public override void Initialize()
{
CreatableTypes()
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();
RegisterAppStart(new AppStart());
}
protected override Cirrious.MvvmCross.ViewModels.IMvxViewModelLocator CreateDefaultViewModelLocator()
{
return MyViewModelLocator ();
}
}
public class MyViewModelLocator : MvxDefaultViewModelLocator
{
public MyViewModelLocator()
{
}
public override IMvxViewModel Load(System.Type viewModelType, IMvxBundle parameterValues, IMvxBundle savedState)
{
if (viewModelType.GetType() == typeof(CartViewModel))
{
var cache = Mvx.Resolve<IMvxMultipleViewModelCache>();
var cachedViewModel = cache.GetAndClear(viewModelType);
if (cachedViewModel == null)
cachedViewModel = base.Load(viewModelType, parameterValues, savedState);
cache.Cache(cachedViewModel);
return cachedViewModel;
}
else
{
return base.Load(viewModelType, parameterValues, savedState);
}
}
}
But somehow with this implementation in place, it is not able to get the ViewModel from cache and cache.GetAndClear call always return null inside ViewModelLocator
implementation. Apart from this place, I don't call cache from any other place from my code so wonder how come it gets removed from cache.
Also, I was wondering, why I simply cannot make use of IOC (i.e. Mvx.RegisterSingleton<ViewModelName>()
and Mvx.Resolve<ViewModelName>()
) to get singleton instance instead of cache? Internal implementation of MvvmCross uses cache and not IOC.