Saber Amani
Saber Amani

Reputation: 6489

Storing user information within a static class

Let's say we want to keep user information after user logged in to application to share its data over multiple classes, what is the best way to do that.

Usually I keep things like this with a property in a static class :

public User CurrentUser { get; set; }

What's your idea ?

Thanks in advance.

Upvotes: 2

Views: 1548

Answers (2)

ColinE
ColinE

Reputation: 70142

What you are proposing is to store the user information within a singleton. This is a well-known pattern that is used quite commonly in desktop applications. There is also a lot of stigma related to the singleton pattern, it is often frowned upon, due to a few drawbacks:

  • Testability, if you have a singleton that is not exposed via interface it is not possible (or easy) to test your code.
  • Scalability, a singleton will always be a singleton so you cannot share this responsibility between multiple instances to allows your application to scale up. This is typically only a concern in server-side application. On the desktop this really does not apply
  • Concurrency, do you have multiple threads accessing your singleton? if so, you need to make it thread safe.

In your context within a desktop application the only one of the above that is likely to be an issue is the first, testability. In that case just define an IUser interface and you're good.

In summary, yes, this is fine. I have used this pattern myself many times in the past.

Upvotes: 3

Mohammed A. Fadil
Mohammed A. Fadil

Reputation: 9377

In WPF: Imagine you have a class called UserInfo that contains all the information needed about the current logged-in user:

// You can use your Application.Current.Resources dictionary to store the
// current logged-in user info.
Application.Current.Resources["UserInfo"] = userInfo;

Then you can retrieve the current user info object anywhere in your application with the following code:

var userInfo = Application.Current.Resources["UserInfo"] as UserInfo;

Upvotes: 3

Related Questions