简体   繁体   中英

Store user account information on a singleton object

I'm building an MVVM Light WPF app in Visual Studio 2015. I've got the following singleton class:

public sealed class AppContextSingleton
{
    private static readonly Lazy<AppContextSingleton> _instance =
        new Lazy<AppContextSingleton>(() => new AppContextSingleton());

    private AppContextSingleton()
    {
    }

    public static AppContextSingleton Instance => _instance.Value;
    public static string UserDisplayName { get; set; }
}

In App.xaml.cs , I have the following code to authenticate the user and fetch the person's display name from the Active Directory:

 protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    var appContext = AppContextSingleton.Instance;

    // Code to authenticate user goes here...

    var displayName = UserPrincipal.Current.DisplayName;
}

Here, I'd like to set the UserDisplayName on the AppContextSingleton and later reference it from the public Instance property. However, the Instance does not give me access to the UserDisplayName property. How would I set this property and then access it from Instance ?

Should I be referencing the Instance or UserDisplayName ? Your help in understanding this is appreciated. Thanks.

The problem is that UserDisplayName is a static property.

That means it is accessed like this: AppContextSingleton.UserDisplayName .

If you change it to an instance property public string UserDisplayName { get; set; } public string UserDisplayName { get; set; } public string UserDisplayName { get; set; } it will work like you want.

Side note 1: I'd remove the Singleton suffix from AppContextSingleton .

Side note 2: Since this is WPF you probably want to implement InotifyPropertyChanged and notify when the value changes since it is mutable.

Side note 3: Does it really need a public set?

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