Search code examples
c#reflectionappdomainremoting

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


From this 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 which says I need to wrap my object in a MarshalByRef type of class and pass it as an argument, and I tried that but I get an exception. Here is what I have (slightly modified from the example given by @Scoregraphic in the first linked thread)

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

I get the exception:

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.

If I remove the tlw argument from the function and remove this assignment, it works just fine. I'm completely stumped on this.


Solution

  • Any privatebinpath must be a subdirectory of any app domains base path. You aren't setting the child app domain base path so it will probably be using the current app domains base path. I'm going to guess that the path to abc.dll is not within a subdirectory of the parent bin folder