tags:

views:

75

answers:

3

So I have this class

public static class MyClass
{
    static MyClass()
    {
        ...
    }
}

Which has no methods, fields or properties. All it does is wire up handlers to static events defined elsewhere.

Since the Type initializer never gets called, because the static class is never actually accessed, the events don't get wired up.

So I was hoping to be able to invoke the type initializer via reflection ala typeof(MyClass).TypeInitializer().Invoke(...) which blows up, with an exception stating that MyClass is an abstract class.

Eventually the app will have other static classes with the same format that correspond to business rules. Before anything is saved to the DB static events are fired that correspond to the type of object being saved. So if what I want to do ends up not being possible, any refactoring recommendations would have to follow that structure.

EDIT:

I may not have been quite clear on exactly what I'm trying to do. Basically I have a data layer, where you can initialize an instance of a DataContext and then when SubmitChanges() is called I check the ChangeSet for for inserts/updates/deletes and trigger static events for each type that is getting inserted/updated/deleted. This all works great, I'm just looking for a way to wire up handlers to the events once when the app starts. So what I was playing with was this:

static DataContext()
{
    System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
        .Where(t => t.Namespace == 'Data.Business')
        .ToList()
        .ForEach( t => { 
            // invoke the static TypeInitializer here,
            // so that it can wire up it's event handlers.
        });
}

I could use a static Initialize method, but since these should only ever be initialized once, I was thinking TypeInitializer.

+5  A: 

Why not just make a static method, i.e. Initialize(), that wires up all the event handlers and just call MyClass.Initialize()?

Richard Hein
Or even a HelloWorld() method. Anything will beat Reflection.
Henk Holterman
Why are folks so opposed to reflection? this will run inside a type initializer, so the performance hit is negligible.
Master Morality
I'm not opposed to reflection, but it's a last choice for most things. Having a separate initialization method is just simpler. What do you get by using reflection in this case when you can totally avoid it? There's other ways to ensure your event handlers are only hooked up once.
Richard Hein
+2  A: 

You can use the RuntimeHelpers.RunClassConstructor method to run the static constructor:

RuntimeHelpers.RunClassConstructor(typeof(MyClass));

However I strongly suggest using another approach to solve your problem... Richard Hein's suggestion seems perfectly good to me.

Thomas Levesque
A: 

Hi Thomas,

There is a correction in your code :

RuntimeHelpers.RunClassConstructor(typeof(MyClass).TypeHandle);

Hope this helps!

Rasik Bihari