为类库挂钩“OnLoad”

时间:2011-12-20 04:57:31

标签: c# .net dll assemblies onload

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

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

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

在.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);
    }
}

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

答案 2 :(得分:0)

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

相关问题