Reputation: 5621
I'm using Jon Skeet's great guide on Singletons in C# found here:
Implementing the Singleton Pattern in C# (Sixth version - using .NET 4's Lazy type)
What I'm trying to do is create a reference class that contains configuration materials used by other classes throughout the program. (settings, themes, etc...)
That reference class has a dependence on a few variables that are provided by a ClientContext object (Scope, TenantID, etc)
For example, there is a settings object that is stored in a database, and needs the TenancyID to pull out the settings for the current scope.
How do I properly use the Singleton pattern, but delay instantiation until a variable is passed to it?
Addendum
In Jon's example, it instantiates itself based on a private static class that cannot be fed a variable.
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
How do I feed a GUID representing an TenantID to a private static readonly variable?
Upvotes: 1
Views: 1791
Reputation: 3024
You could make your singleton instance a Lazy<T>
. This won't instantiate until you attempt to access it. For more examples, look here.
Edit: I just realized Jon Skeet even calls this out specifically in his guide.
Upvotes: 1