开发者

Invoke static type initializers via reflection perhaps

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.

EDIT 2:

I've read up on MEF and this really provides a way to do what I wanted to do.


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


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

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

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


Make the following correction in your code:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜