Mr. 笑哥
Mr. 笑哥

Reputation: 283

WPF Prism User Object

I am new to WPF and MVVM Prism. I have been an ASP.NET developer for more than 5 years and recently switched to a WPF project.

I am currently using Prism 5.0 with Unity. The main purpose of following the pattern is to implement modularity and loose coupling.

My question is this: I would like to make my User Object universal and accessible across all modules.

This is what I've done so far. Upon start up, users are greeted with a login screen (LoginView.xaml) in Login project. LoginViewModel will then validate credentials. Upon successful validation, LoginViewModel will then pass this retrieved object to a static class in Infrastructure project. Since user login is only single / universal instance, I have created a static class under Infrastructure project to hold the user object.

I have tried GenericPrincipal, while it does persist data across views, it's not sophisticated enough to hold data that I need. Hence I went for static class instead.

Does anyone have a better suggestion around it?

Upvotes: 2

Views: 391

Answers (1)

Lucas Damiani
Lucas Damiani

Reputation: 77

Instead of registering your User object in a static class, I suggest you to register the User instance in the Unity container itself.

In your LoginViewModel, you should get an instance of your IUnityContainer class.

public LoginViewModel(IUnityContainer container)
{
    Container = container;
}

In your Login method, you register your user object:

private void Login(object obj)
{
    ...
    if (user.Authenticated)
    {
        Container.RegisterInstance("CurrentUser", user); 
    }
    ...
}

To access your object, you use the following code snippet:

Container.Resolve<YourUserClassHere>("CurrentUser");

For more details see: Persisting user credentials in WPF w/Unity and MVVM

Upvotes: 2

Related Questions