Static ctors in VB.NET, C# vs C++
.NET instantiates static declarations (class members, for example) differently than C++, which results in a very frustrating side effect. As a C++ programmer of 10 years (much of it using MFC), it was easy to properly initialize an abstract class factory with a derived class. This is because C++ instantiates all static declarations before executing main().
For example, the base class would contain 'protected static m_Instance' and a helper class would be used to create the proper derived instance for m_Instance, eg the application code would contain a static declaration of the helper class, and the helper classes ctor would contain something like 'BaseClass.SetInstance (new DerivedClass)'. This technique guaranteed that the factory would be initialized before main() was executed.
Unfortunately, .NET handles static fields differently, e.g. the ctor for the static class is not instantiated before main() executes. Instead, it is not until a member of the class is explicitly accessed do any static ctors execute, which prevents the above factory pattern from working correctly.
I've spent way too much time trying to find a 'hook' in .NET that I could use to execute some initialization code like the above BaseClass.SetInstance (new DerivedClass) snippet. I've looked at deriving from classes to override ctors/methods, hooking into events, etc. for classes like Assembly, Application, Processes, ProcessModule, AppDomain, etc. and still haven't been able to find a way to have a block of initialization code execute either 1) before the application starts running, or 2) after the assembly is loaded but before any references to it are resolved.
Any suggestions?
|