I have a singleton and when I call it from my UnitTest I get
“System.TypeInitializationException was unhandled by user code
Message=The type initializer for ‘mycompany.class’threw an exception”
public sealed class MySingleton
{
private static MySingleton instance = new MySingleton();
private MySingleton()
{
ConnectionString = GetConnectionstring();
}
public static MySingleton NewConnectivity
{
get { return instance ?? (instance = new MySingleton()); }
}
public string ConnectionString { get; set; }
private static string GetConnectionstring()
{
return "bla";
}
}
I can’t see much from what is there… Bu if you have a static field-initialiser, why does the property need to check for null? Actually I suspect this is due to the field initialiser running before other code in the static constructor etc.
I would try removing the field initialiser – but note that without this there is an edge case (timing/thread-race) that could result in more than one object being created. If that isn’t acceptable there are lots of ways of avoiding this thread race.