I have an application with user-login which representates a "lifetime" object till the user logs out. I'm using MVVM Light but don't know how to use the SimpleIoC (with the Messenger) correctly.
Currently I save the object in the MainViewModel as CurrentUser
Property of my custom User
object and pass it to other ViewModels via constructor and save it there as a Property too. But with that I have the issue, that at some places the object gets overwritten / created new.
This is probably the wrong way to do it as i figured out that the SimpleIoC can simply return the registered instances with GetInstance<>()
and if needed a Key.
So the right way is it to create a User
object with Key to get it in needed classes, modify and save it so the other classes can get the updated value when calling (or PropertyChanged possible?), right?
I tried to create it like that, but the object is obviously not updated:
public MainViewModel()
{
RegisterMessenger();
CurrentUser = SimpleIoc.Default.GetInstance<User>("123");
_dataService = SimpleIoc.Default.GetInstance<IDataService>();
Messenger.Default.Send(new NotificationMessage("GoToLoginPage"));
}
public User CurrentUser
{
get { return _currentUser; }
set { Set(ref _currentUser, value); }
}
public User CurrentPageViewModel
{
get { return _currenPageViewModel; }
set { Set(ref _currentPageViewModel, value); }
}
public void RegisterMessenger()
{
Messenger.Default.Register<NotificationMessage>(this, message =>
{
switch (message.Notification)
{
case "GoToLoginPage":
if (_loginViewModel == null)
_loginViewModel = new LoginViewModel(_dataService);
CurrentPageViewModel = _loginViewModel;
break;
// Other cases...
});
}
}
// -------------------------------------------------------------------------
public LoginViewModel(IDataService dataService)
{
UserObj = SimpleIoc.Default.GetInstance<User>("123");
_dataService = dataService;
LoginCommand = new RelayCommand(LoginExecute, LoginCanExecute);
}
Would it also be better, if I call the ViewModels with GetInstance<SomeViewModel>()
.. but then, how I pass paramters to them and let them stay alive / recreate / destroy?
Would be nice if someone can point me out the right way, thanks!