I have the next static class:
public static class GlobalVar
{
public static string DatabaseName = "ProjectDatabase.mdf";
public static AdminClass Admin;
public static string TruePath = AppDomain.CurrentDomain.BaseDirectory;
public static string TimeStampPattern = "dd/MM/yyyy HH:mm";
static GlobalVar()
{
TruePath = TruePath.Remove(TruePath.Length - 1);
Admin = new AdminClass("Admin", "Admin");
GlobalStatus = new Dictionary<string, string>();
string Query = "SELECT * FROM global_status";
DataTable Types = MyAdoHelper.ExecuteDataTable(GlobalVar.DatabaseName, Query);
foreach (DataRow Status in Types.Rows)
{
GlobalStatus.Add(Status["title"].ToString(), Status["info"].ToString());
}
}
public static Dictionary<string, string> GlobalStatus;
public static string BasePath = HttpContext.Current.Request.ApplicationPath;
}
The GlobalStatus is a dictionary receives the custom errors the site may return. When I launch the project (Microsoft Visual Web developer 2008), it gives an error:
Object reference not set to an instance of an object.
when trying to get a value from GlobalStatus (eg. GlobalVar.GlobalStatus["Page_NoAccess"]).
Only after a minute, when I launch the project again, it runs fine.
How can I fix this, like force it the browser to wait until it fills GlobalStatus. I need this class to initialize only once, since it contains global variables which I don't want to be recalled every browser request.
Thanks
First of all, I want to suggest you global vars concept in an object-oriented code is a bad idea.
In order to solve your problem, you need to use built-in, out-of-the-box ASP.NET approaches: global application class.
Use Application_Start
event handler and invoke initialization processes during this event .
Anything opposed to above statement is a bad idea.
Now... how to do it better
Initialize()
, Start()
.... Call them in Application_Start
event of global application class.UPDATE & NOTE I suggest this MSDN article about static constructors in order to understand why these are a bad idea in ASP.NET initialization.