Csharp/C#教程:为类库挂钩“OnLoad”分享


为类库挂钩“OnLoad”

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

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

您需要挂钩到AssemblyLoad事件。

请参阅https://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 inn" + i_Assembly.Location, Ex); } } 

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

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

上述就是C#学习教程:为类库挂钩“OnLoad”分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/949504.html

(0)
上一篇 2021年11月17日
下一篇 2021年11月17日

精彩推荐