There are numerous posts available on alternatives to global state, but I have lingering questions regarding implementation in a web environment.
In ASP.NET, values stored in the session are practically global variables, but it seems you can’t reasonably store, e.g., authenticated username, permissions, etc. across pages and events without resorting to the Session[] collection. (I would typically use dependency injection, but you wouldn’t want to pass these values in the viewstate/url to the client.)
So I take that global state is a necessary evil in web development (due to the stateless nature of HTTP) and the answer is to just use it responsibly. What is a good facade pattern for implementation? A static class such as the one below that just gets and sets values in the session doesn’t do much to mask the global state.
public class SessionWrapper
{
public static string UserName
{
get { return Convert.ToString(Session["UserName"]); }
set { Session["UserName"] = value; }
}
public static bool IsAuthenticated
{
get { return Convert.ToBoolean(Session["IsAuthenticated"]); }
set { Session["IsAuthenticated"] = value; }
}
}
Global variables are problematic but global values are fine. So if you want to mitigate the “problems” of global state simply make those objects immutable (I don’t see how DI is all that relevant).
The
Userproperty of theHttpContextobject is useful for storing such state since it needs to be available to every part of your application but can only be assigned early in the pipeline.So, just come up with your own implementation of
System.Security.Principal.IPrincipalthat has the extra properties you want and assign it toHttpContext.Current.Userduring, say, theAuthenticateRequestevent.