开发者

Persisting logged in user information

开发者 https://www.devze.com 2023-04-05 19:08 出处:网络
I know this is a simple concept, but I nee开发者_运维百科d some help. I\'m creating a winforms app, in c#, and I\'m trying to organize my code. The first screen is a log in, and once the user is authe

I know this is a simple concept, but I nee开发者_运维百科d some help. I'm creating a winforms app, in c#, and I'm trying to organize my code. The first screen is a log in, and once the user is authenticated I return the users details. How/where should I store these details so that I don't have to retrieve them again each time I want to use them?

Thank you!


Along the lines of what the others have said about the global static class, but with some sample code :

public class UserInfo
{
    private int userID;

    public int UserID
    {
        get { return userID; }
    }

    private string userName;

    public string UserName
    {
        get { return userName; }
    }

    public UserInfo(int userID, string userName)
    {
        this.userID = userID;
        this.userName = userName;
    }
}

public static class GlobalInfo
{
    private static UserInfo currentUser;

    public static UserInfo CurrentUser
    {
        get { return currentUser; }
        set { currentUser = value; }
    }
}

So, after the user has logged in, save the logged in info :

GlobalInfo.CurrentUser = new UserInfo(123, "Bob Jones");

When you need to fetch info :

UserInfo userInfo = GlobalInfo.CurrentUser;


You could create a global static class as answered in this question or look at a Singleton Pattern implementation

... or read this question "Global variable approach in C# Windows Forms application? (is public static class GlobalData the best)" for more options.


I would go with a singleton as @brodie says, but implemented as an instance of the user details object pushed into a DI container. For example, Ninject supports binding to a instance via BindToConstant. So you would have your LoggedInUser instance (details of the logged in user) created when the user logs in, then Bind<LoggedInUser>.ToConstant(myLoggedInUser) (from memory). Then if you need to get the logged in user you would just pull the current instance from the DI container (via something like kernel.Get<LoggedInUser>()).

0

精彩评论

暂无评论...
验证码 换一张
取 消