C# 如何使用加载的DLL程序集';引用到其他程序集的方法?

C# 如何使用加载的DLL程序集';引用到其他程序集的方法?,c#,.net,dllimport,appdomain,C#,.net,Dllimport,Appdomain,我有两个组件。我将classlib1添加到classLib2引用中。就像这样: 我是这样用的: namespace ClassLibrary2 { public class Class1 { public Class1() { } public int GetSum(int a , int b) { try {

我有两个组件。我将classlib1添加到classLib2引用中。就像这样:

我是这样用的:



namespace ClassLibrary2
{
    public class Class1
    {
        public Class1()
        {

        }

        public int GetSum(int a , int b)
        {
            try
            {
                ClassLibrary1.Class1 ctx = new ClassLibrary1.Class1();
                return ctx.Sum(a, b);
            }
            catch
            {
                return -1;
            }

        }
    }
}

我还想使用AppDomain动态加载(class1lib和Class2Lib)另一个C#项目。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Reflection.Emit;

namespace WcfService3 { public partial class Default : System.Web.UI.Page { public static ArrayList arryFiles { get; set; } protected void Page_Load(object sender, EventArgs e) {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        arryFiles = new ArrayList();
        List<byte[]> binaryList = new List<byte[]>();
        // string fileName = @"S:\Source\Yusuf.Karatoprak\plugin\ClassLibrary1.dll";
        DirSearch(@"S:\Source\Yusuf.Karatoprak\plugin");
        foreach (var filePath in arryFiles)
        {
            FileStream fileStream = File.OpenRead(filePath.ToString());
            byte[] buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, Convert.ToInt32(fileStream.Length));
            fileStream.Dispose();
            binaryList.Add(buffer);
            //Assembly[] assBefore = AppDomain.CurrentDomain.GetAssemblies();

            //AppDomain.CurrentDomain.Load(buffer);

            //Assembly[] assAfter = AppDomain.CurrentDomain.GetAssemblies();

            //Type t = Type.GetType("ClassLibrary1.Class1,ClassLibrary1");
        }

        new AssemblyLoader().LoadAndCall(binaryList);
    }
    static void DirSearch(string sDir)
    {
        try
        {
            foreach (string f in Directory.GetFiles(sDir, "*.dll"))
            {
                if (!arryFiles.Contains(f))
                    arryFiles.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                if (d != null)
                {
                    foreach (string f in Directory.GetFiles(d, "*.dll"))
                    {
                        if (!arryFiles.Contains(f))
                            arryFiles.Add(f);
                    }
                    DirSearch(d);
                }
                else
                    break;
            }

        }
        catch (System.Exception excpt)
        {
            throw new Exception(excpt.Message);

        }
    }
}

public class AssemblyLoader : MarshalByRefObject
{
    public void LoadAndCall(List<byte[]> binaryList)
    {
        Assembly loadedAssembly=null;
        Assembly[] assBefore = AppDomain.CurrentDomain.GetAssemblies();
        foreach (byte[] binary in binaryList)
        {
            loadedAssembly = AppDomain.CurrentDomain.Load(binary);
        }
        Assembly[] assAfter = AppDomain.CurrentDomain.GetAssemblies();
        object[] tt = { 3, 6 };
        Type type = loadedAssembly.GetType("ClassLibrary2.Class1");
        object loaded = loadedAssembly.CreateInstance("ClassLibrary2.Class1", true, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, new object[] { }, null, null);
       // object obj = Activator.CreateInstance(type);



        ObjectCreateMethod inv = new ObjectCreateMethod(type); //Specify Type
        Object obj = inv.CreateInstance();

        MethodInfo minfo = type.GetMethod("GetSum", BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance);
        int x = (int)minfo.Invoke(obj, new Object[] { 3, 6 });
        Console.WriteLine(x);
    }
}

public class ObjectCreateMethod
{
    delegate object MethodInvoker();
    MethodInvoker methodHandler = null;

    public ObjectCreateMethod(Type type)
    {
        CreateMethod(type.GetConstructor(Type.EmptyTypes));
    }

    public ObjectCreateMethod(ConstructorInfo target)
    {
        CreateMethod(target);
    }

    void CreateMethod(ConstructorInfo target)
    {
        DynamicMethod dynamic = new DynamicMethod(string.Empty,
                    typeof(object),
                    new Type[0],
                    target.DeclaringType);
        ILGenerator il = dynamic.GetILGenerator();
        il.DeclareLocal(target.DeclaringType);
        il.Emit(OpCodes.Newobj, target);
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Ret);

        methodHandler = (MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker));
    }

    public object CreateInstance()
    {
        return methodHandler();
    }
}

使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControl;
使用System.IO;
运用系统反思;
使用系统集合;
使用System.Reflection.Emit

命名空间WcfService3 { 公共部分类默认值:System.Web.UI.Page { 公共静态ArrayList arryFiles{get;set;} 受保护的无效页面加载(对象发送方、事件参数e) {

}
受保护的无效按钮1\u单击(对象发送者,事件参数e)
{
arryFiles=newarraylist();
List binaryList=新列表();
//字符串文件名=@“S:\Source\Yusuf.Karatoprak\plugin\ClassLibrary1.dll”;
DirSearch(@“S:\Source\Yusuf.Karatoprak\plugin”);
foreach(arryFiles中的var filePath)
{
FileStream FileStream=File.OpenRead(filePath.ToString());
byte[]buffer=新字节[fileStream.Length];
Read(缓冲区,0,Convert.ToInt32(fileStream.Length));
Dispose();
添加(缓冲区);
//程序集[]assBefore=AppDomain.CurrentDomain.GetAssemblys();
//AppDomain.CurrentDomain.Load(缓冲区);
//程序集[]assAfter=AppDomain.CurrentDomain.getAssemblys();
//类型t=Type.GetType(“ClassLibrary1.Class1,ClassLibrary1”);
}
新建AssemblyLoader().LoadAndCall(二进制列表);
}
静态void DirSearch(字符串sDir)
{
尝试
{
foreach(Directory.GetFiles(sDir,*.dll)中的字符串f)
{
如果(!arryFiles.Contains(f))
添加(f);
}
foreach(Directory.GetDirectories(sDir)中的字符串d)
{
如果(d!=null)
{
foreach(Directory.GetFiles(d,*.dll)中的字符串f)
{
如果(!arryFiles.Contains(f))
添加(f);
}
DirSearch(d);
}
其他的
打破
}
}
捕获(系统异常excpt)
{
抛出新异常(异常消息);
}
}
}
公共类AssemblyLoader:MarshalByRefObject
{
公共void LoadAndCall(列表二进制列表)
{
Assembly loadedAssembly=null;
程序集[]assBefore=AppDomain.CurrentDomain.GetAssemblys();
foreach(二进制列表中的字节[]二进制)
{
loadedAssembly=AppDomain.CurrentDomain.Load(二进制);
}
程序集[]assAfter=AppDomain.CurrentDomain.getAssemblys();
对象[]tt={3,6};
Type Type=loadedAssembly.GetType(“ClassLibrary2.Class1”);
object loaded=loadedAssembly.CreateInstance(“ClassLibrary2.Class1”,true,BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance,null,新对象[]{},null,null);
//object obj=Activator.CreateInstance(类型);
ObjectCreateMethod inv=新建ObjectCreateMethod(类型);//指定类型
Object obj=inv.CreateInstance();
MethodInfo minfo=type.GetMethod(“GetSum”,BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance);
intx=(int)minfo.Invoke(obj,新对象[]{3,6});
控制台写入线(x);
}
}
公共类ObjectCreateMethod
{
委托对象MethodInvoker();
MethodInvoker methodHandler=null;
公共ObjectCreateMethod(类型)
{
CreateMethod(type.GetConstructor(type.EmptyTypes));
}
公共ObjectCreateMethod(ConstructorInfo目标)
{
创建方法(目标);
}
void CreateMethod(ConstructorInfo目标)
{
DynamicMethod dynamic=新的DynamicMethod(string.Empty,
类型(对象),
新类型[0],
目标(去极化型);
ILGenerator il=dynamic.GetILGenerator();
il.DeclareLocal(目标.DeclaringType);
发射(操作码.Newobj,目标);
发射(操作码Stloc_0);
发射(操作码Ldloc_0);
发射(操作码Ret);
methodHandler=(MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker));
}
公共对象CreateInstance()
{
返回methodHandler();
}
}
}

为什么无法加载和异常错误返回给我:


外观内部异常:无法加载文件或程序集“ClassLibrary1”,但我加载了Classlib2和Classlib1。class2取决于classlib1如何使用classlib1方法我想在加载程序集后使用GetSum(inta,intb)方法:

不太确定在动态加载期间是否可以将对另一个DLL的引用链接到程序集。至少我不知道。但总的来说

  • 如果你在谈论插件,不要将它们链接在一起。若并没有,那个么就并没有理由使用基于插件的系统

  • 我会尝试检查主机应用程序的
    .netframework
    版本,看看它加载了哪些插件。可能是版本控制冲突

希望这能有所帮助。

对此有所发现。处理resolve事件似乎是最后的努力。如果你没有选择就试试吧。替换为您的S:\Source\Yusuf.Karatoprak\plugin。您还可以尝试处理该事件,以查看从二进制文件加载的内容


@节目主持人,干杯

您的
“S:\Source\Yusuf.Karatoprak\plugin”
是否包含ClassLibrary1.dll?是的,您可以确定!包含它。谢谢你发现这有点相似。处理resolve事件似乎是最后的努力。只是tr