views:

185

answers:

3

In web applications user login information is usually stored in a session but how about windows applications? Is using a singleton the right thing to do? Should I just use a static property?

Lets say that I store the login information in a static property ApplicationController. LoggedInUser. When a user logs in successfully, that property is set. Before a successful login, LoggedInUser returns null. Then when calling for an example OrdersService from my OrderListPresenter-class, I use the LoggedInUser as a parameter.

var service = new OrdersService();
var orderCollection = service.GetOrdersByUserID(
    ApplicationController.LoggedInUser.ID);

Ok, this works but it also makes writing the unit tests somewhat harder. I don't like working with singletons / static members from my unit tests.

Maybe I could inject the ApplicationController to every class which needs to access logged in user? Any other ideas?

What do you think is the best way to handle this?

+1  A: 

Injection is a good answer. You'll probably find other things useful to put in an ApplicationController, and it makes it easy to unit-test.

Jason Cohen
+2  A: 

I would create a CurrentContext object which contains a CurrentUser field and pass it around to all my presenters.

Avoid singleton, that could be problematic to unit test or if you decide to expand your application later on.

George Mauer
+1  A: 

Depending on what you wish to do with the user identity consider putting it onto System.Threading.Thread.CurrentPrincipal. If your application has SecurityPermissionFlag.ControlPrincipal permission then just set CurrentPrincipal when you have one. Also note that System.Environment.UserName has the logged in Windows user identity.

There's always a cost to rolling your own type when a built-in type already exists and does what (or close to what) you want.

Howard Hoffman