Running code at app startup - static variables

  • Thread starter Thread starter greek_bill
  • Start date Start date
G

greek_bill

Hi,

I quite often need to have a system of classes providing alternative
implementions of some concept and need each class to register itself
with a manger (singleton) class. A good example might be some kind of
image loader, where you wrap the functionality to load an image of a
particular format in a class and a manager class maintains an
association between file extension and handler class.

In native C++ I would generally do this by having some kind of static
variable who's contructor would register a handler with the manager.

I tried doing the same in C++/CLI and came across the problem that
static member variables (and static constructors) don't get
initialized until the first time you use that class! Which of course
is a problem for me because I never intent on using that class
directly. The manager class would give me a pointer to a base class/
interface that all handle classes derive from.

Am I doing this all wrong? Is there a better way? Is there a way to
run code at app startup (without having to have a-priori knowledge of
each class)?


On a slightly different, but relevant, note, given that managed code
has (and exposes) a lot more knowledge about type information, is
there a way to store a reference to a type? I can see how that would
be useful for class factories, where you associate, say, an integer or
a string with a type. I had a quick look around the documention and I
could see how delegates (c'tors with standard interface) or even
System::Reflection::ConstructorInfo would be relevant, but long-
winded. Ideally something like :

Dictionary<int, Type>^ factory;

Type^ obj = factory[5]();


Thanks,

Bill
 
Oooh....System::Activator::CreateInstance....how cool! :)

Still need a way of (automatically) registering types with the manager
class though.
 
Hmm, interesting, it appears that while I can't have a global variable
of a managed type, having a gcroot<T^> is fine, i.e.

public ref class Foo
{...};

Foo^ g_Foo = gcnew Foo();

error C3145: 'g_Foo' : global or static variable may not have managed
type 'Foo ^'
may not declare a global or static variable, or a member of a
native type that refers to objects in the gc heap


however, the following works

gcroot<Foo^> g_Foo = gcnew Foo();

and the Foo c'tor gets called during app startup.



Still, is there a better way of doing this? Doing the above doesn't
feel right for some reason. How would you do this sort of thing in C#
for example?
 
Still, is there a better way of doing this? Doing the above doesn't
feel right for some reason. How would you do this sort of thing in C#
for example?

You can tag the types with a custom attribute and then use reflection to
find and load them at startup.
 
Back
Top