将值从不同的应用程序域传递到主要(主要)应用程序域

Passing value from a different app domain to the primary (Main) app domain

从这个 post, I am able to load a dll into an app domain and get the types in that dll and print them in the temporary domain's function if I want to. But I now want to pass these types back to the primary domain (which has Main). I found this thread 开始,它说我需要将我的对象包装在 class 的 MarshalByRef 类型中并将其作为参数传递,我试过了但我得到了一个异常。这是我所拥有的(根据第一个链接线程中@Scoregraphic 给出的示例稍作修改)

    public class TypeListWrapper : MarshalByRefObject
    {
            public Type[] typeList { get; set; }
    }

    internal class InstanceProxy : MarshalByRefObject
    {
        public void LoadLibrary(string path, TypeListWrapper tlw)
        {
            Assembly asm = Assembly.LoadFrom(path);

            var x = asm.GetExportedTypes();//works fine

            tlw.typeList = x;//getting exception on this line
        }
    }

    public class Program
    {

        public static void Main(string[] args)
        {
            string pathToMainDll = Assembly.GetExecutingAssembly().Location;
            string pathToExternalDll = "/path/to/abc.dll";

            try
            {
                AppDomainSetup domainSetup = new AppDomainSetup
                {
                    PrivateBinPath = pathToMainDll 
                };
                AppDomain domain = AppDomain.CreateDomain("TempDomain", null, domainSetup);
                InstanceProxy proxy = domain.CreateInstanceFromAndUnwrap(pathToMainDll , typeof(InstanceProxy).FullName) as InstanceProxy;
                TypeListWrapper tlw = new TypeListWrapper();
                if (proxy != null)
                {
                    proxy.LoadLibrary(pathToExternalDll , tlw);
                }


                AppDomain.Unload(domain);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }

            Console.ReadLine();
        }
    }

我得到异常:

Could not load file or assembly 'abc, Version=1.0.0.5, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

如果我从函数中删除 tlw 参数并删除此赋值,它就可以正常工作。我完全被这个难住了。

任何 privatebinpath 都必须是任何应用域基本路径的子目录。您没有设置子应用程序域基本路径,因此它可能会使用当前的应用程序域基本路径。我猜测 abc.dll 的路径不在父 bin 文件夹

的子目录中