如何使用它引用到其他组件加载的DLL组件“的方法呢?组件、加载、方法、使用它

2023-09-04 04:19:06 作者:好菇娘、中国造

我有2个组件。我加入classlib1到classLib2参考。像那样:

i have 2 assemblies. i added classlib1 into classLib2 references. like that:

和我用这样的:



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;
            }

        }
    }
}

此外,我想动态加载(class1lib和Class2Lib)其它C#项目使用的AppDomain。  

Also i want to load (class1lib and Class2Lib) another C# project dynamically by using AppDomain.


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;

命名空间WcfService3 {     公共部分类默认:System.Web.UI.Page     {         公共静态的ArrayList arryFiles {获得;组; }         保护无效的Page_Load(对象发件人,EventArgs的)         {

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();
    }
}

}

}

为什么不能加载和异常错误回我:

Why can not load and Exception error return to me:

看内部异常:无法加载文件或程序ClassLibrary1的,但我装Classlib2 ABD Classlib1。等级2取决于classlib1如何使用classlib1方法,我想用GetSum(INT一,int b)在负​​载组件之后方法:

Look inner exception: Could not load file or assembly 'ClassLibrary1 But i loaded Classlib2 abd Classlib1 . class2 depends on classlib1 how to use classlib1 method i want to use GetSum(int a , int b) method after load assemblies:

推荐答案

发现这个有点类似的问题。处理解决事件似乎是最后的努力。试试看,如果您运行的选项。请用您的S:\来源\ Yusuf.Karatoprak \插件。您也可以尝试处理 AppDomain.AssemblyLoad 事件,看看从你的二进制文件被加载。

Found this somewhat similar question. Handling the resolve event seems to be a last ditch effort. Just try it if you run out of options. Replace with your S:\Source\Yusuf.Karatoprak\plugin. You can also try handling the AppDomain.AssemblyLoad event, to see what was loaded from your binaries.

@programmerist,干杯!

@programmerist, cheers!