How can I share ‘global’ application level context data between all objects living in an application. I’m thinking in terms of the currently logged on user record, which branch the user has opened to work on for a session, etc. How can I make this information available to all my forms and the classes they use for business logic services?
Just having one big global singleton AppContext object doesn’t appeal to me, but I can’t think of anything else right now. Maybe extend the Application class to offer a context service to all forms? I haven’t worked on desktop apps for some time and have come to rely on e.g. the ever present Session object in ASP.NET.
I think the concept of a browser “session” was invented to maintain state across browser requests. That really isn’t an issue for desktop apps. You could define a typed class with info about the user: id, email, name, etc. Basically whatever you would store in session. When someone logs in, create a new instance and assign it to a static variable. When they log out, set the static variable to null.
If you wanted it to behave more like HttpSessionState does (arbitrary key/value pairs), replace your typed class with a Hashtable.
EDIT
Depending on what you are planning to keep in session, my answer might vary, but here is a singleton-like class I quickly came up with.
From any form in your application you could easily reference
AppContext.Current. I am not sure if this quite answers your question, but this would be my first approach.