This is a slight variance of this question: Possible to use a singleton with a non-default constructor in C#?
I have a class that takes parameters for it’s constructor. I would like to make this singleton such that the parameters are taken upon initialising the singleton and thus would not need to be passed in each time the instance is retrieved.
My solution (which is not elegant) for this is to have a CreateInstance() static method that takes the parameters and constructs the singleton instance. I would then have another static method GetInstance() which would be parameterless to obtain the singleton instance. In code, I would then need to ensure the logic calls CreateInstance before any calls to GetInstance. However, I cannot enforce this at compile time. I can, however, check at runtime by throwing an exception in GetInstance if it is called before CreateInstance.
Is there anyway I can achieve this behaviour with compile time enforcement? Or at the very least, is there a better way of doing the same thing?
There is no way to do it at compile time, because that would be like asking the compiler “can you prove that code X is never executed before code Y is executed, in the presence of multiple threads?”. It cannot be done.
As for the runtime behavior of your design, I think this is as good as it can ever be.
You can make it slightly better by exposing a
Func<SingletonType>property in your singleton class. When someone asks for the singleton instance and the instance has not already been created, your class would call this “factory method” to construct the singleton. If the factory method isnull, then you either throw an exception or (if applicable) construct using some default parameters.What this does is essentially defer the construction of the singleton until it’s actually needed for the first time, so it’s some improvement. But the underlying principle is the same.
Update:
As
LukeHpoints out, this is pretty much whatLazy<T>does (.NET 4 only). If possible, use that one instead of writing your own.