Search code examples
.netwcfassemblies

.Net: Running code when assembly is loaded


Is it possible to run some code when an assembly is loaded, without doing anything specific in the loading code? What I am looking for is like a static constructor on a type.

Eg:

Assembly A does not know about Assembly B, but B does know about A. Assembly A needs to know certain things about B if B is loaded. When Assembly B is loaded by the runtime (referenced, or explicit), I want a piece of code (static method or attribute) to be executed that calls a method in Assembly A.

The root cause of this problem is unknown types being encountered when serializing a type in A that contains types from B not known at compile time as interfaces are used.


Solution

  • The CLR supports module initializers. You'd have to hack C++/CLI code or ilasm.exe to use them.

    UPDATE: directly supported in C# as well since .NET 5 with the [ModuleInitializer] attribute