开发者

TypeInitializationException in my singleton. How can I fix it?

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 'myco开发者_如何转开发mpany.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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜