如何将当前应用程序域的程序集动态加载到 C# 项目? [英] How to load assemblies to the current app domain to the c# project dynamically?

查看:44
本文介绍了如何将当前应用程序域的程序集动态加载到 C# 项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将第三方 assemblies 动态 加载到项目中,并使用 reflection 创建它们类型的实例.

I'm trying to load third party assemblies dynamically to the project and use reflection to create instance of their types.

我用过:

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 implementation 异常,如下所示:

However, I keep getting The method is not implemented exception while I try to create instance of one of their type as follow:

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并执行:

However, if I directly add reference to Assembly1, Assembly2 and Assembly3 in the project and do:

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

我也不例外

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

I just wanted to know what I'm doing wrong? How do I load assemblies to the project dynamically. I'm guessing since creation of Class1 instance depends on another assembly Assembly1 and Assembly2, so it's failing. So, how do I load all the dependent assemblies dynamically to the appdomain/loadcontext.

非常感谢您的回答.

推荐答案

当使用ad.AssemblyResolve += MyAssemblyResolveHandler"时,我得到了由 'cdie' 描述的无限循环.

When using "ad.AssemblyResolve += MyAssemblyResolveHandler", I got the infinite loop described by 'cdie'.

所以我尝试了几件事.以下是通过 MSDNs LoadFrom 链接

So I tried a couple of thing. The following was via the MSDNs LoadFrom link

public object InitClassFromExternalAssembly(string dllPath, string className)
{
    try
    {
        Assembly assembly = Assembly.LoadFrom(dllPath);
        Type type = assembly.GetType(className);
        var instance = Activator.CreateInstance(type);
        return instance;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

显然,Assembly.LoadFrom 方法需要 DLL 的完整路径.

Apparently, the Assembly.LoadFrom method requires the full path of the DLL.

请注意在链接中通过 LoadFrom 加载程序集可能出现的问题.

Please note the possible problems loading an assembly via LoadFrom in the link.

此外,' 包含的链接上面的 ArcangelZith' 有一些有趣的想法.

Also, the link included by 'ArcangelZith' above has some interesting ideas.

这篇关于如何将当前应用程序域的程序集动态加载到 C# 项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆