Monday, July 7, 2008

Static Classes and Members in ASP.NET Web Applications

Do not use static classes in web applications. They will overwrite each other when different users access the same web pages at the same time. Concurrency issues.

Static methods are ok, along with any parameters passed to them. Any local variables inside the static methods are ok as well.

DO NOT Use public static class or static properties in web application, unless their values should be the same for all users.

Following statics are ok.

static void Main(string[] args)
{
Utils.LogError("aa"); //testing statics
Utils.LogError("bb");
}


class Utils
{
//all these vars get initialized the first time any static method is called from this class
//and used for all other calls
static readonly string _path = GetPathFromRegKey();

public static void LogError(string msg) //testing statics
{
//_path is initialized only once above & is used for all calls to LogError
string logFile = _path + "\\LogFile.txt";
Console.WriteLine(msg + " " + logFile);
}


public static string GetPathFromRegKey()
{
string path = "";

//Get path...

return path;
}


Useful Links:

http://blogs.iis.net/brian-murphy-booth/archive/2007/06/15/static-shared-or-not-who-cares.aspx

http://gbracha.blogspot.com/2008/02/cutting-out-static.html

http://www.yoda.arachsys.com/csharp/singleton.html

http://msdn.microsoft.com/en-us/library/ms954629.aspx

0 comments: