升级到 6.0 版后 MvvmCross App 无法启动

MvvmCross App Won't Start after upgrading to version 6.0

我将我的应用程序升级到了 MvvmCross 6.0 版。现在它进入启动画面并且什么都不做。通过查看控制台,我可以看到服务正在启动。这是我的 app.cs:

public class App : MvxApplication
{
    public override void Initialize()
    {
        MPS.ApplicationName = Settings.ApplicationName;
        EventLog.ApplicationName = Settings.ApplicationName;
        BlobCache.ApplicationName = Settings.ApplicationName;

        CreatableTypes()
            .EndingWith("Service")
            .AsInterfaces()
            .RegisterAsLazySingleton();

        CreatableTypes()
            .EndingWith("Singleton")
            .AsInterfaces()
            .RegisterAsSingleton();

        //RegisterAppStart(new CustomAppStart());
        //RegisterNavigationServiceAppStart<LoginViewModel>();
        RegisterAppStart<LoginViewModel>();
    }

}

这是非常基本的。我已经转换到新的导航系统,因此是 RegisterNavigationServiceAppStart。那将不再解决,所以我直接回到 RegisterAppStart。启动画面出现,然后停止。如果重要,splashscreen.cs 如下:

[Activity(
    Label = "@string/ApplicationName"
    , MainLauncher = true
    , Icon = "@drawable/icon"
    , Theme = "@style/Theme.Splash"
    , NoHistory = true)]
    //, ScreenOrientation = ScreenOrientation.Landscape)]
public class SplashScreen : MvxSplashScreenActivity
{
    public SplashScreen()
        : base(Resource.Layout.SplashScreen)
    {
    }
}

它很普通,但我知道事情已经发生了变化。我的setup.cs如下:

public class Setup : MvxAndroidSetup
{
    //public Setup(Context applicationContext)
    //    : base(applicationContext)
    //{
    //}

    protected override IMvxApplication CreateApp()
    {
        return new App();
    }

    //protected override IMvxTrace CreateDebugTrace()
    //{
    //    return new DebugTrace();
    //}

    protected override IMvxAndroidViewPresenter CreateViewPresenter()
    {
        return new MvxAppCompatViewPresenter(AndroidViewAssemblies);
    }

    protected override void FillValueConverters(IMvxValueConverterRegistry registry)
    {
        base.FillValueConverters(registry);
        registry.AddOrOverwrite("DateToStringConverter", new DateToStringConverter());
        registry.AddOrOverwrite("FloatToStringConverter", new FloatToStringConverter());
        registry.AddOrOverwrite("DecimalToStringConverter", new DecimalToStringConverter());
        registry.AddOrOverwrite("BoolToViewStatesConverter", new BoolToViewStatesValueConverter());
        registry.AddOrOverwrite("ShipmentToOriginConverter", new ShipmentToOriginConverter());
        registry.AddOrOverwrite("ShipmentToDestinationConverter", new ShipmentToDestinationConverter());
        //registry.AddOrOverwrite("CustomName2", new AnotherVerySpecialValueConverter("Summer"));
    }

    protected override void FillTargetFactories(MvvmCross.Binding.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
    {
        base.FillTargetFactories(registry);
        registry.RegisterCustomBindingFactory<EditText>("FocusText",
                                                  textView => new MvxEditTextFocusBinding(textView));
        registry.RegisterCustomBindingFactory<TextView>("FocusChange",
                                                  textView => new MvxTextViewFocusChangeBinding(textView));
        //registry.RegisterCustomBindingFactory<MvxSpinner>("ItemSelected",
        //                                          spinner => new MvxSpinnerItemSelectedBinding(spinner));
    }

    protected override IEnumerable<Assembly> AndroidViewAssemblies => new List<Assembly>(base.AndroidViewAssemblies)
    {
        typeof(MvvmCross.Droid.Support.V7.RecyclerView.MvxRecyclerView).Assembly
    };

}

我对它所做的唯一更改是删除了构造函数。根据 6.0 版的文档,构造函数不再有参数,所以我认为没有理由调用它。有人可以帮忙吗?

** 更新 **

我加了一个MainApplication.cs如下:

[Application]
public class MainApplication : MvxAppCompatApplication<Setup, App>
{
    public MainApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }
}

这让我通过了初始屏幕,但挂断了 LoginViewModel 的初始化。

* 日志 *

也许这会有所帮助。以下是事件日志条目:

2018-04-17 12:17:06 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Primary start
2018-04-17 12:17:06 [TRACE] (MvvmCross.Core.MvxSetup) Setup: FirstChance start
2018-04-17 12:17:06 [TRACE] (MvvmCross.Core.MvxSetup) Setup: PlatformServices start
2018-04-17 12:17:06 [TRACE] (MvvmCross.Core.MvxSetup) Setup: MvvmCross settings start
2018-04-17 12:17:06 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Singleton Cache start
2018-04-17 12:17:06 [TRACE] (MvvmCross.Core.MvxSetup) Setup: ViewDispatcher start
2018-04-17 12:17:06 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Bootstrap actions
2018-04-17 12:17:07 [TRACE] (MvvmCross.Logging.MvxLog) No view model type finder available - assuming we are looking for a splash screen - returning null
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: StringToTypeParser start
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: CommandHelper start
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: PluginManagerFramework start
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Create App
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: NavigationService
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Load navigation routes
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: App start
2018-04-17 12:17:07 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Application Initialize - On background thread
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: ViewModelTypeFinder start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: ViewsContainer start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Views start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: CommandCollectionBuilder start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: NavigationSerializer start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: InpcInterception start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: InpcInterception start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: LastChance start
2018-04-17 12:17:08 [TRACE] (MvvmCross.Core.MvxSetup) Setup: Secondary end
2018-04-17 12:17:08 [TRACE] (MvvmCross.Logging.MvxLog) AppStart: Application Startup - On UI thread

我稍微追查了一下。它挂在视图模型中的 Initialize() 上。我创建了一个测试来演示:

public class FirstViewModel : MvxViewModel
{

    public FirstViewModel()
    {
        Task.Run(async () =>
        {
            var l = await ListDataSource.GetLocations();
            var m = l;
        });
    }

    public async override Task Initialize()
    {
        await base.Initialize();
        var l = await ListDataSource.GetLocations();
        var m = l;
    }

}

如果我在两个 var m = l 上设置一个断点,它将到达构造函数中的那个,但永远不会到达初始化中的那个。 GetLocations 是:

    public async static Task<LocationList> GetLocations()
    {
        ListServiceClient client = NewClient();

        LocationList ret = null;
        bool TryCache = false;

        try
        {
            //ret = await client.GetLocationListAsync();
            ret = await Task<LocationList>.Factory.FromAsync((asyncCallback, asyncState) => client.BeginGetLocationList(asyncCallback, asyncState),
               (asyncResult) => client.EndGetLocationList(asyncResult), null);

            client.Close();
            await BlobCache.LocalMachine.InsertObject("Locations", ret, DateTimeOffset.Now.AddDays(Settings.CacheDays));
        }
        catch (TimeoutException ex)
        {
            client.Abort();
            EventLog.Error(ex.ToString());
            TryCache = true;
        }
        catch (CommunicationException ex)
        {
            client.Abort();
            EventLog.Error(ex.ToString());
            TryCache = true;
        }
        catch (Exception ex)
        {
            EventLog.Error(ex.ToString());
            TryCache = true;
        }

        if (TryCache)
        {
            try
            {
                ret = await BlobCache.LocalMachine.GetObject<LocationList>("Locations");
            }
            catch (KeyNotFoundException)
            {
                ret = null;
            }
        }

        return ret;
    }

如果您在 Client.Close() 上设置断点,如果从构造函数调用它会到达那里,但如果它从 Initialize 调用则不会到达那里。

为了让大家受益,Jim 创建了一个 bug in MvvmCross GitHub repo. One of the MvvmCross project contributors provided a workaround for his problem and blogged about it

我的问题是双重的。首先,当您使用 Android 升级到 6.0 版时,您现在必须包含一个 MainApplication.cs,如下所示:

[Application]
public class MainApplication : MvxAppCompatApplication<Setup, App>
{
    public MainApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
    {
    }
}

否则,您将卡在 SplashScreen 上。其次,您需要知道您显示的第一个 ViewModel 中的 Initialize 必须是同步的。正如 @Ale_lipa 提到的,一位 MvvmCross 作者写了一篇博客 post 解释了为什么会这样以及如何处理它。

https://nicksnettravels.builttoroam.com/post/2018/04/19/MvvmCross-Initialize-method-on-the-first-view-model.aspx

简而言之,如果您使用的是 SplashScreen,并且您确实需要将第一个 ViewModel 的 Initialize 设为 Async,则可以按如下方式添加 CustomAppStart:

public class CustomMvxAppStart<TViewModel> : MvxAppStart<TViewModel>
     where TViewModel : IMvxViewModel
{
     public CustomMvxAppStart(IMvxApplication application, IMvxNavigationService navigationService) : base(application, navigationService)
     {
     }

    protected override void NavigateToFirstViewModel(object hint)
     {
         NavigationService.Navigate<TViewModel>();
     }
}

在你App.cs中,替换你的:

RegisterAppStart<FirstViewModel>();

与:

RegisterCustomAppStart<CustomMvxAppStart<FirstViewModel>>();

这将使您的第一个 Initialize 成为异步的。我只确定它适用于 Android,并且仅当您使用 SplashScreen 时才有效。

除了 Jim 的 post,我有一个 SplashScreen,我的启动视图模型取决于这是否是第一次激活,关于它的决定是在核心项目的 AppStart.Startup()方法。

我的应用程序现在似乎可以正常运行,并且处于较高水平,密钥 类 如下所示:

Core.App

public class App : MvxApplication
{           
    public override void Initialize()
    {
        // IoC registrations here

        RegisterAppStart(new AppStart(this));            
    }   
}

Core.App开始

public class AppStart : MvxAppStart
{
    public AppStart(IMvxApplication application) : base(application)
    {
    }

    protected override async void Startup(object hint = null)
    {
        base.Startup(hint);

        // logic to navigate to intro viewmodel or home viewmodel
    }
}

Droid.Setup

public class Setup : MvxAppCompatSetup<App>
{                
    protected override IMvxApplication CreateApp()
    {
        return new Core.App();
    }

    protected override void InitializeIoC()
    {
        base.InitializeIoC();
        // Custom IoC initialization
    }

    protected override IMvxAndroidViewPresenter CreateViewPresenter()
    {            
        return new MvxAppCompatViewPresenter(AndroidViewAssemblies);
    }

    protected override IEnumerable<Assembly> AndroidViewAssemblies => new List<Assembly>(base.AndroidViewAssemblies)
    {
        typeof(NavigationView).Assembly,
        typeof(FloatingActionButton).Assembly,
        typeof(Android.Support.V7.Widget.Toolbar).Assembly,
        typeof(Android.Support.V4.Widget.DrawerLayout).Assembly,
        typeof(Android.Support.V4.View.ViewPager).Assembly,
    };

    protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
    {
        MvxAppCompatSetupHelper.FillTargetFactories(registry);
        base.FillTargetFactories(registry);
    }
}

我很清楚,这不是与这个问题的代码相关的问题,而是与我遇到的升级到 MvvmCross 6.0 直接相关。

只是添加这个,因为它可能会帮助某人节省几个小时,因为官方文档 reg 中没有提到这个东西。现在正在升级。

因此,就我而言,这是 Setup class:

中重载方法的问题
    public override IEnumerable<Assembly> GetViewAssemblies()
    {
        var list = new List<Assembly>();
        list.AddRange(base.GetViewAssemblies());
        list.Add(typeof(App).GetTypeInfo().Assembly);

        return list;
    }

    public override IEnumerable<Assembly> GetViewModelAssemblies()
    {
        var list = new List<Assembly>();
        list.AddRange(base.GetViewModelAssemblies());
        list.Add(typeof(CoreApp).GetTypeInfo().Assembly);

        return list;
    }

我需要它,因为我的 Views 和 ViewModel 位于不同的项目中。升级后,应用 运行 未超过初始化,没有任何错误。删除这些后,一切都开始正常工作。 (显然,最新版本 会自动处理 )。