.Net: Running code when assembly is loaded

Robert Wagner picture Robert Wagner · Feb 2, 2009 · Viewed 15.5k times · Source

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.

Answer

Hans Passant picture Hans Passant · Feb 2, 2009

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