As part of trying to propose an answer to another question, I wanted to create a Dictionary
of self-registering Singleton instances. Specifically, something like this:
public abstract class Role
{
public static Dictionary<string, Role> Roles = new Dictionary<string, Role>();
protected Role()
{
_roles.Add(this.Name, this);
}
public abstract string Name { get; }
}
public class AdminRole : Role
{
public static readonly AdminRole Instance = new AdminRole();
public override string Name { get { return "Admin"; } }
}
However, the AdminRole
constructor isn't being called unless I access Instance
, so it's not being added to the Roles
dictionary. I know I could just instantiate the dictionary using { AdminRole.Instance.Name, Admin Role}
, but I'd like adding new roles to not require the Role
class to change.
Any suggestions? Is this even a good design for accessing Singletons by string?
The line of code to test the result is:
var role = Role.Roles["Admin"];
It's successful if you don't get a KeyNotFound
exception (or null
).
There can be an explicit initialization of Role
(such as Role.Initialize()
), but not of the subclasses - the idea is to be able to add a subclass so the dictionary has it, without ever needing to change anything pre-existing.