Search code examples
mvvmcross

mvvmcross Init method is not called if I inherit froma base ViewModel which is derived from MvxViewModel


First I'm using mvvmcross version 3.0.13. When a class is inherited from a base class, which is inherited from MvxViewModel, the Init method won't be called from IoC. Current ugly workaround is to call the Init in the constructor. Could this be a bug or is there another pattern to use?

In both classes (base and child of that base) it won't be called. For example:

public class BaseViewModel : MvxViewModel
{
    protected CDataImportService DataImportService { get; private set; }
    protected CSettingService SettingService { get; private set; }
    protected CDataService DataService { get; private set; }
    protected CDocumentService DocumentService { get; private set; }

    public BaseViewModel(IDataService objDataService, IDataImportService objDataImportService, IDocumentService objDocumentService, ISettingService objSettingService)
    {
        DataImportService = (CDataImportService)objDataImportService;
        SettingService = (CSettingService)objSettingService;
        DataService = (CDataService)objDataService;
        DocumentService = (CDocumentService) objDocumentService;
    }

    public void Init()
    {
        Mvx.Trace("Init called in {0}", GetType().Name);
    }
}

public class DocumentsViewModel : BaseViewModel
{
    public MenuViewModel(IDataService objDataService, IDataImportService objDataImportService, IDocumentService objDocumentService, ISettingService objSettingService)
        : base(objDataService, objDataImportService, objDocumentService, objSettingService)
    {
    }
}

Solution

  • IOC on it's own does not call the Constructor-Init-Reload-Start sequence.

    IOC is a general C# service, and only calls the constructor part.

    If you want the entire sequence called then you can access this via the IMvxViewModelLoader object - e.g Mvx.Resolve<IMvxViewModelLoader>().LoadViewModel(MvxViewModelRequest<MyViewModel>.GetDefaultRequest(), null);

    By default, this will use the Default ViewModel Locator to create a view model instance - https://github.com/MvvmCross/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross/ViewModels/MvxDefaultViewModelLocator.cs


    If it helps, for some more information: