Reputation: 675
Answers to other questions about singleton implementation state that a constructor should be private for a singleton class. But UWP main App
singleton class derived from Windows.UI.Xaml.Application
has a public constructor. XML documentation generated by VS for it says:
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
When I try to create a second instance on mouse event I get
Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
So why is constructor public and how is singleton implemented to force only one instance of App
to exist?
Upvotes: 0
Views: 373
Reputation: 59410
Singleton pattern
The singleton design pattern restricts the instantiation of a class to one single instance. How that is achieved is not defined by the pattern itself, because the pattern is independent of programming languages. You can e.g. use a .Instance
property or a .GetInstance()
method - or even name it whatever you like, which may confuse people, but it will still be a singleton.
Using a private constructor seems to be good practice, because it is helpful as it will generate a compiler error when trying to use the private constructor. But: some programming languages don't even have a private
keyword.
Obviously, UWP chose to restrict the number of instances in a way that causes an exception at runtime.
Implementation
Looking at the call stack, the catastrophic failure happens in
at Windows.UI.Xaml.Application..ctor()
at UWP.App..ctor() in ...\App.xaml.cs:line 29
at UWP.App.OnLaunched(LaunchActivatedEventArgs e) in ...\App.xaml.cs:line 43
So the App class constructor calls the base class constructor which throws an exception. Since Windows.UI.Xaml.dll
is not a .NET DLL, I can't look into it with dotPeek or dnSpy.
Upvotes: 1