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

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

问题描述

我正在尝试将第三方组件 动态加载到项目中,并使用 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") 

但是,在尝试创建以下类型之一的实例时,我不断得到该方法未实现异常:

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 实例取决于另一个程序集 Assembly1 Assembly2 ,所以失败了。因此,如何将所有依赖程序集动态加载到 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'.

所以我尝试了几件事。以下是通过MSDN的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方法需要完整路径

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天全站免登陆