简体   繁体   中英

How to implement Singleton for Xamarin forms using PRISM?

I am working on Xamarin.Forms using PRISM library for MVVM architecture.

So, the problem is whenever I navigating between pages using INavigationService always the class/ViewModel is instantiating newly, so already assigned strings are becoming empty/null. I am registering page and ViewModel in App.Xaml.cs as below:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterForNavigation<LoginPage, LoginViewModel>();
}

How to handle not to instantiate newly always or need to Instantiate only one time throughout the app working.

What you're trying to do is not supported for a variety of reasons. Suffice it to say a Singleton ViewModel is a very bad practice and causes a lot of problems. While we cannot stop you from registering the ViewModel as a singleton with the container this WILL introduce bugs into your app.

Appropriate Ways

You haven't really provided any details of what it is you're trying to instantiate but one of these methods should work for you.

Use IInitialize or INavigationAware.OnNavigatedTo

public class LoginViewModel : IInitialize
{
    public void Initialize(INavigationParameters parameters)
    {
        // Initialize anything you need to for the life cycle of your ViewModel here
    }
}

Use a Singleton Service

public class SomeService : ISomeService
{
    public string Username { get; set; }
}

public partial class App : PrismApplication
{
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterForNavigation<LoginPage, LoginViewModel>();
        containerRegistry.RegisterSingleton<ISomeService, SomeService>();
    }
}

public class LoginViewModel
{
    private ISomeService _someService { get; }

    public LoginViewModel(ISomeService someService)
    {
        _someService = someService;
        UserName = _someService.UserName;
    }

    // simplified for example
    public string UserName { get; set; }

    private void DoLogin()
    {
        _someService.UserName = UserName;

    }
}

I should also point out that if you are looking for something to last from one session to the next of your app running then you could use the built in IApplicationStore which exposes the Properties Dictionary and SavePropertiesAsync from the Application in an interface that keeps your code testable.

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