有没有人知道有没有办法挂钩到一个"OnLoad“事件,以便在程序集加载时运行一些操作?
具体地说,我正在为应用程序创建一个插件。加载插件的DLL并开始使用对象,但问题是我需要在发生任何事情之前动态加载另一个程序集。此程序集不能复制到应用程序的目录中,必须保持对其不可见。
发布于 2011-12-20 05:01:32
您需要连接到AssemblyLoad
事件。
Refer- http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyload.aspx
发布于 2015-01-07 15:58:58
在Assembly DLL中编写Main()函数从未被.NET框架调用,这真是令人遗憾。微软似乎忘记了这一点。
但是您可以很容易地自己实现它:
在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);
}
}
显然,在对该程序集做任何其他操作之前,您应该在一开始就调用此函数。
发布于 2017-11-22 20:29:29
C#不提供这样做的方法,但是底层的IL代码通过module initializers提供。您可以使用诸如Fody/ModuleInit之类的工具将一个特别命名的静态C#类转换为一个模块初始化器来运行,该初始化器将在加载dll时运行。
https://stackoverflow.com/questions/8570999
复制