Call static type initializers via reflection, perhaps

So i have this class

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

Who does not have methods, fields or properties. All he does is wire handlers for static events defined elsewhere.

Since the type initializer is never called because the static class never accesses reality, events are not fired.

So, I was hoping that I could call the type initializer using reflection ala typeof(MyClass).TypeInitializer().Invoke(...), which explodes, except that it MyClassis an abstract class.

Ultimately, the application will have other static classes with the same format that complies with business rules. Before anything is stored in the database, static events corresponding to the type of object being saved will be fired. Therefore, if what I want to do turns out to be impossible, any recommendations for refactoring will have to follow this structure.

EDIT:

, , . , DataContext, , SubmitChanges(), ChangeSet // , //. , , . :

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 event handlers.
        });
}

Initialize, , TypeInitializer.

2:

MEF, , .

+3
3

, (), MyClass.Initialize()?

+5

RuntimeHelpers.RunClassConstructor :

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

... .

+5

In the code, enter the following adjustment:

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

Hope this helps!

0
source

Source: https://habr.com/ru/post/1765533/


All Articles