为类库挂钩“OnLoad”

有没有人知道是否有办法挂钩到“OnLoad”事件,以便在程序集加载时运行某些操作?

具体来说,我正在为应用程序创建一个插件。 插件的DLL被加载并且对象开始被使用,但问题是我需要在发生任何事情之前动态加载另一个程序集。 此程序集无法复制到应用程序的目录中,并且必须对其保持不可见。

您需要挂钩到AssemblyLoad事件。

请参阅http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyload.aspx

很遗憾在.NET框架中从不调用在Assembly DLL中编写Main()函数。 微软似乎忘记了这一点。

但您可以自己轻松实现它:

在DLL程序集中,您添加以下代码:

 using System.Windows.Forms; public class Program { public static void Main() { MessageBox.Show("Initializing"); } } 

然后在加载此DLL的Exe程序集中添加此函数:

 using System.Reflection; void InitializeAssembly(Assembly i_Assembly) { Type t_Class = i_Assembly.GetType("Program"); if (t_Class == null) return; // class Program not implemented MethodInfo i_Main = t_Class.GetMethod("Main"); if (i_Main == null) return; // function Main() not implemented try { i_Main.Invoke(null, null); } catch (Exception Ex) { throw new Exception("Program.Main() threw exception in\n" + i_Assembly.Location, Ex); } } 

显然你应该在开始使用该程序集之前调用此函数。

C#没有提供这样做的方法,但底层的IL代码通过模块初始化器完成 。 您可以使用Fody / ModuleInit等工具将特殊名称的静态C#类作为模块初始化程序运行,该模块初始化程序将在加载dll时运行。