DLL中的ResolveEventHandler(类库)

时间:2013-01-31 13:20:24

标签: c# events dll assemblyresolve

在C#中有ResolveEventHandler事件,如果它们不在应用程序目录中,则加载外部dll。

要在winform应用程序中使用它,我在Program.cs Main()函数中注册事件,如下所示:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly);

然后每次触发事件时都会调用ResolveAssembly函数:

    static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
    {
        //MessageBox.Show(String.Format("Assembly {0} is missing", args.Name));


        //This handler is called only when the common language runtime tries to bind to the assembly and fails.

        //Retrieve the list of referenced assemblies in an array of AssemblyName.
        Assembly MyAssembly, objExecutingAssemblies;
        string strTempAssmbPath = "";
        string AssemblyName = new AssemblyName(args.Name).Name;

        objExecutingAssemblies = Assembly.GetExecutingAssembly();
        AssemblyName[] arrReferencedAssmbNames = objExecutingAssemblies.GetReferencedAssemblies();

        //Loop through the array of referenced assembly names.
        foreach (AssemblyName strAssmbName in arrReferencedAssmbNames)
        {
            //Check for the assembly names that have raised the "AssemblyResolve" event.
            if (strAssmbName.Name == AssemblyName)
            {
                //Build the path of the assembly from where it has to be loaded.                
                strTempAssmbPath = @"C:\PowerVision\libraries\" + AssemblyName + ".dll";
                break;
            }

        }
        //Load the assembly from the specified path.                    
        MyAssembly = Assembly.LoadFrom(strTempAssmbPath);

        //Return the loaded assembly.
        return MyAssembly;
    }

问题是如何在类库中添加/调用此事件?

我有一个类库(DLL),它有3个对外部DLL的引用。我不想将这些dll复制到应用程序目录中,也不希望将它们放入应用程序的子目录中。这些DLL应保留在特定的外部文件夹中(因此使用该事件)。

问题是我不知道在DLL(类库)中放置此事件的位置:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly);

1 个答案:

答案 0 :(得分:0)

您只需将事件注册放在DLL中的某个地方,在任何3个外部DLL被引用之前被调用。

顶级DLL中对象的构造函数将是第一个查找的位置。但是,如果该对象是在这3个外部DLL之一中的对象的子类型,那么您可能需要为该对象创建父对象,并首先调用父对象,并在其中添加事件注册父母的构造函数。

E.g。如果您的DLL是UserControl,它基于另外一个UserControl,它位于这3个外部DLL之一中,如下所示:

public partial class TopLevelUserControl: ExternalDllUserControl
{
    InitializeComponent();
}

然后您可能需要编写如下代码:创建一个名为TopLevelUserControlLauncher的新用户控件,并将TopLevelUserControl放在该userControl中,停靠。然后编写如下代码:

public partial class TopLevelUserControlLauncher: UserControl
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly);
    InitializeComponent(); // this will construct TopLevelUserControl
}