Static class Object reference not set to an instance of an object
-
13-06-2021 - |
Question
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
Solution
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
- For everything that you find that are settings use AppSettings or settings files.
- Using static constructors for application initialization is a bad idea. Create a static class with static methods like
Initialize()
,Start()
.... Call them inApplication_Start
event of global application class. - Static classes with static fields and data in a multi-threaded environment like ASP.NET are a big fail. More than a thread can initialize your application at once. How your code manages this situation?.
- Forget global variables concept in an object-oriented piece of software. Use settings (like I said in 1st point) or create constants or fields (static or instance ones) as part of the class that's going to consume it.
UPDATE & NOTE I suggest this MSDN article about static constructors in order to understand why these are a bad idea in ASP.NET initialization.