I have referred to Jon Skeet's article here (http://csharpindepth.com/articles/general/singleton.aspx), the sixth version.
However, I have some private variables that I want initialized once, and be used by methods in this supposedly singleton class. I initialized them in the private constructor, but soon found out, that they are null when invoking the methods, in a multi-threaded scenario (Task.Run).
When debugging, I observed that the private constructor doesn't called twice (which should be) when I call out for an "Instance", and so I assume that my private variables, shouldn't be null at that point in time already (succeeding "Instance" calls).
Any idea on how should I declare, initialize, and use these variables?
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
// my private variables
private readonly string _plantCode;
private Singleton()
{
var appSettings = ConfigurationManager.AppSettings;
string _plantCode = appSettings["PlantCode"] ?? "Not Found";
}
public SomeMethod()
{
var temp = _plantCode; // <== _plantCode becomes null here!
}
}
This is the problem:
string _plantCode = appSettings["PlantCode"] ?? "Not Found";
That isn't assigning to the instance variable - it's declaring a new local variable. You just want:
_plantCode = appSettings["PlantCode"] ?? "Not Found";
(This would happen with the same code in a normal class, by the way - it has nothing to do with the fact that it's a singleton.)
See more on this question at Stackoverflow