Reputation: 6438
I had a class:
public class Constant
{
public static string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
which would throw exception on LIVE: Type initialize failed for Constant ctor
If I change the class to:
public class Constant
{
public static string ConnString
{
get
{
return ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
}
}
it works. I wasted 2 hours behind this but I still don't know why would this happen. Any ideas?
Note: The 1st class used to work on DEV environment but not on LIVE. The 2nd class works on DEV and also on Production.
I am using VS2010 on production and Asp.Net 4.0 Website project.
I am totally amazed by this inconsistency to say the least!
Edit: This class was in App_Code
folder.
Upvotes: 1
Views: 1252
Reputation: 57593
I think the main difference is:
Constant
class is initializedConnString
property is accessed (so probably initialization phase is complete)Upvotes: 2
Reputation: 73
It may well be that for whatever reason, the ConfigurationManager wasn't initialised when Constant was initialised in the first example. However, Class 2 will go and fetch the property in ConfigurationManager when it's actually needed, rather than when your Constant class is initialised.
Upvotes: 0
Reputation: 7212
Apparently this line
ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString
will throw an exception on LIVE.
In the first case however this happens in your class constructor so the type initialization fails.
In the second case the exception is delayed until you use the property.
Upvotes: 1