是否可以在加载程序集时运行一些代码,而无需在加载代码中执行任何特定操作?我正在寻找的是一个类型的静态构造函数.
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.
例如:
程序集 A 不知道程序集 B,但 B 知道 A.如果加载了 B,程序集 A 需要知道有关 B 的某些信息.当运行时(引用或显式)加载程序集 B 时,我希望执行一段调用程序集 A 中方法的代码(静态方法或属性).
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.
这个问题的根本原因是在序列化 A 中的类型时遇到未知类型,该类型包含来自 B 的类型,因为使用接口在编译时未知.
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.
推荐答案CLR 支持 模块初始值设定项.您必须破解 C++/CLI 代码或 ilasm.exe 才能使用它们.
The CLR supports module initializers. You'd have to hack C++/CLI code or ilasm.exe to use them.
更新:从 .NET 5 开始,C# 也直接支持 [ModuleInitializer] 属性
UPDATE: directly supported in C# as well since .NET 5 with the [ModuleInitializer] attribute
更多推荐
.Net:加载程序集时运行代码
发布评论