c# - 如何动态加载程序集到当前应用程序域到c#项目?

标签 c# .net .net-assembly

我正在尝试将第三方程序集 动态 加载到项目中,并使用反射 来创建它们类型的实例。

我用过:

Assembly.LoadFrom("Assembly1.dll")
Assembly.LoadFrom("Assembly2.dll")
Assembly.LoadFrom("Assembly3.dll") 

另外,试过:

AppDomain.CurrentDomain.Load("Assembly1.dll")
AppDomain.CurrentDomain.Load("Assembly2.dll")
AppDomain.CurrentDomain.Load("Assembly3.dll") 

但是,当我尝试创建其中一种类型的实例时,我不断收到 The method is not implemented 异常:

Assembly.LoadFrom("Assembly1.dll")
Assembly.LoadFrom("Assembly2.dll")
Assembly assembly=  Assembly.LoadFrom("Assembly3.dll")
Type type=assembly.GetType("Assembly3.Class1")
object instance=Activator.CreateInstance(type); //throws exception at this point

但是,如果我直接添加引用到项目中的 Assembly1、Assembly2 和 Assembly3 并执行:

Assembly3.Class1 testClass=new Assembly3.Class1();

我没有异常(exception)

我只是想知道我做错了什么?如何将程序集动态加载到项目中。我猜是因为 Class1 实例的创建依赖于另一个程序集 Assembly1Assembly2,所以它失败了。那么,如何将所有依赖程序集动态加载到 appdomain/loadcontext

非常感谢您的回答。

最佳答案

要解决依赖关系,您需要处理 AppDomain.AssemblyResolve Event

using System;
using System.Reflection;

class ExampleClass
{
    static void Main()
    {
        AppDomain ad = AppDomain.CurrentDomain;

        ad.AssemblyResolve += MyAssemblyResolveHandler;

        Assembly assembly = ad.Load("Assembly3.dll");

        Type type = assembly.GetType("Assembly3.Class1");

        try
        {
            object instance = Activator.CreateInstance(type);
        } 
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static Assembly MyAssemblyResolveHandler(object source, ResolveEventArgs e) 
    {
        // Assembly.LoadFrom("Assembly1.dll")
        // Assembly.LoadFrom("Assembly2.dll")

        return Assembly.Load(e.Name);
    }
}

MyAssemblyResolveHandler 为每个未加载的程序集触发,包括依赖项。

关于c# - 如何动态加载程序集到当前应用程序域到c#项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795721/

相关文章:

c# - 你如何在 C# 中使用 XMLSerialize 枚举类型的属性?

.net - .NET 核心程序集中非常特殊的 PublicKey

c# - 实例化所有实现通用接口(interface)实例的类

c# - 如何获取引用程序集的物理路径

c# - 如何在 XDocument 中添加命名空间和声明

c# - 在 GridView 上添加行得到 "Specified argument was out of the range of valid values"

c# - 在 if 语句中使用排他或,C#

c# - 将属性添加到 XMLROOT 元素名称

c# - 升级到 .NET 4.7 后为 "Predefined type System.ValueTuple is not defined or imported"

.net - 在没有 CLR/.NET 的情况下使用 Visual Studio 创建表单应用程序