Is IMvxAndroidCurrentTopActivity a singleton?

2019-05-23 10:06发布

问题:

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?

回答1:

In the default MvvmCross setup that interface is implemented as a singleton - so is guaranteed to return the same instance as long as your app is in memory

See InitializePlatformServices in https://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);
    }

This singleton nature is really part of the definition of this interface - so if you were to override the android setup, then you should really keep this registration as a singleton.


At a general level, I'm afraid there is only way to currently tell in MvvmCross whether an interface or object is registered as a singleton or as a dynamic creation-on-demand object - to look at the source

  • e.g. https://github.com/slodge/MvvmCross/search?q=IMvxAndroidCurrentTopActivity&ref=cmdform.

In the future, this could possibly be achieved via XML comments or via some kind of naming convention, but I don't believe these are planned currently and also neither of those techniques would be compile time checked.