简体   繁体   中英

Keeping a service alive throughout the lifetime of the application

I have a simple service interface I am using to synchronize data with a server via HTTP. The service interface has a method to start and stop the synchronization process. The idea is to start the synchronization process after the user signs in, and stop the synchronization at the end of the application before the user signs out. The synchronization service will check for new messages every few minutes, and then notify the ViewModel(s) of new/changed data using the MvxMessenger plugin.

What is the recommended way to ensure the synchronization service lives for the duration of the app? I am currently using a custom IMvxAppStart which registers the service interface as a singleton, and then holds a static reference to the service interface. Is that enough to keep the service alive for the lifetime of the app, or is there a better way?

public class App : MvxApplication
{
    public override void Initialize()
    {
        ...
        RegisterAppStart(new CustomAppStart());
    }
}

public class CustomAppStart : MvxNavigatingObject, IMvxAppStart
{
    public static ISyncClient SynchronizationClient { get; set; }

    public void Start(object hint = null)
    {
        SynchronizationClient = Mvx.Resolve<ISyncClient>();
        ShowViewModel<SignInViewModel>();
    }
}

public interface ISyncClient
{
    void StartSync();
    void StopSync();

    bool IsSyncActive { get; }
}

You don't need a static property for this. When you register the Interface as a singleton, the IoC do the work for you. Example: In one of our apps wee need a state-property with important data for the whole lifetime of the app.

The models who need this state, just uses following code snippet:

protected IApplicationState AppState
{
    get { return _appstate ?? (_appstate = Mvx.GetSingleton<IApplicationState>()); }
}
private IApplicationState _appstate;

But: You can do it also with a static property. But in this case you don't need a singleton-value in the IoC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM