Reputation: 1437
I build an application that the user have to login in order to continue.
The user that has been connected, assigned into CurrentAccountProperty in the current ViewModel.
Now, How do I make this current connected account accessible to all the other ViewModels that have interaction with it and its data?
For example, ViewModels that manipulate its login details, ViewModels, for example, that add somthing to its RecentActivities property and so on..
Should I hold a reference to the current account? somthing like CurrentAccount in each ViewModel that uses this object?
Thanks.
Upvotes: 0
Views: 1162
Reputation: 760
If you're using (dependency injection/IOC container) the way I normally do this is by using dependency injection - create a contextviewmodel make it a singleton and then inject it into the constructor of each viewmodel that needs to use it. Therefore it gets created when the app loads, populated when you need it to be populated and then persisted as a context through out the app.
So if you're using DI and an IOC. If you're using something like Unity - use the ControlledContainerLifetime() option to make it a singleton.
You'll have to add the contextviewmodel into the container and also (if you're using unity etc - resolve it) so the first time you need it - inject it and update the login property you need. Afterwards - if you need to use it in another view model - just inject it again either with a [Dependency] attribute or into your constructor. Then because the contextviewmodel is a singleton it will contain the same instance of the contextviewmodel with the property previously set. Let me know if you need a code sample.
So long as you inject this view model into any of the other classes you use - you'll be able to use it and it will persist for the lifetime of your app.
Upvotes: 1
Reputation: 4538
Well I usually Export
(MEF) property I set after user is logged in.
/// <summary>
/// Gets or sets LoggedUser.
/// </summary>
[Export]
public UserInfo LoggedUser { get; set; }
Then I Import
everywhere I need access to logged user.
/// <summary>
/// Gets or sets LoggedUser.
/// </summary>
[Import]
public UserInfo LoggedUser { get; set; }
Of course you can use any IoC container as well. And you should use some kind of IoC when you talk about MVVM.
Upvotes: 1