My project has many handler classes that derive from a common base class, and I am trying to get each of the handler classes to install themselves in a static table in the base class, and my first thought was a static constructor.
But this seems to use a super-lazy evaluation, and since I never refer to the derived classes directly (always by the handler
table), this never triggers the static ctor.
Super simple stupid example:
public abstract class BlahBase
{
public static readonly Dictionary<string, BlahBase> Handlers = new();
public static BlahBase FindHandler(string name)
{
// look up in the Handlers table, return to caller
}
// other stuff
}
public class BlahFooHandler : BlahBase
{
static BlahFooHandler()
{
Handlers.Add("foo", typeof(BlahFooHandler));
}
// other stuff
}
public class BlahBarHandler : BlahBase
{
static BlahBarHandler()
{
Handlers.Add("bar", typeof(BlahBarHandler));
}
// other stuff
}
The idea is that BlahFooHandler
and BlahBarHandler
's static constructors would install themselves in the base Handlers
table, and none of this apparently works without directly touching the derived class to trigger the static constructor. I'm trying to make this entirely dynamic.
I've spent much time looking into static constructors, and most questions revolve around lazy behavior: I want non lazy behavior.
An alternate approach is to use reflection and/or an [Attribute]
on each of the handler classes, both of which I'm comfortable doing, but wonder if I'm missing an obvious language facility to achieve this.