Reputation: 16080
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";
}
}
Upvotes: 1
Views: 2892
Reputation: 17973
A TypeInitializationException
occurs when your static constructor in the class "mycompany.class" throws an exception. Try to put a breakpoint in your static constructor and step into each call? Do you get some other exception in that case?
Upvotes: 2
Reputation: 1064114
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.
Upvotes: 2