2

IMvxAndroidCurrentTopActivity can be used to get the current top activity in a MvvmCross Android application.

The question is: Will MvvmCross create a new instance of this interface as soon as the top activity changes or does it reuse the same instance and just change the Activity property.

Background: I would like to take that interface as a constructor dependency in a class that is registered as singleton.
Will it work?

4

1 回答 1

9

在默认的 MvvmCross 设置中,该接口被实现为单例 - 因此只要您的应用程序在内存中,就保证返回相同的实例

参阅InitializePlatformServiceshttps://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Droid/Platform/MvxAndroidSetup.cs#L76

    protected override void InitializePlatformServices()
    {
        var lifetimeMonitor = new MvxAndroidLifetimeMonitor();
        Mvx.RegisterSingleton<IMvxAndroidActivityLifetimeListener>(lifetimeMonitor);
        Mvx.RegisterSingleton<IMvxAndroidCurrentTopActivity>(lifetimeMonitor);
        Mvx.RegisterSingleton<IMvxLifetime>(lifetimeMonitor);

        Mvx.RegisterSingleton<IMvxAndroidGlobals>(this);

        var intentResultRouter = new MvxIntentResultSink();
        Mvx.RegisterSingleton<IMvxIntentResultSink>(intentResultRouter);
        Mvx.RegisterSingleton<IMvxIntentResultSource>(intentResultRouter);

        var viewModelTemporaryCache = new MvxSingleViewModelCache();
        Mvx.RegisterSingleton<IMvxSingleViewModelCache>(viewModelTemporaryCache);
    }

这种单例性质实际上是该接口定义的一部分——因此,如果您要覆盖 android 设置,那么您应该真正将此注册保留为单例。


在一般层面上,恐怕目前只有一种方法可以在 MvvmCross 中判断一个接口或对象是注册为单例还是作为动态按需创建对象 -查看源代码

将来,这可能会通过 XML 注释或某种命名约定来实现,但我不相信这些是目前计划的,而且这些技术都不会在编译时检查。

于 2013-07-04T09:36:58.517 回答