CreateInstanceAndUnwrap and Domain

2019-02-09 06:13发布

问题:

I have a property whose instance I want to be in other domain.

public ModuleLoader Loader
        {
            get
            {

                if(_loader == null)
                    _loader = (ModuleLoader)myDomain.CreateInstanceAndUnwrap(
                              this.GetType().Assembly.FullName,
                              "ModuleLoader",
                              false, 
                              System.Reflection.BindingFlags.CreateInstance,                                  
                              null, 
                              null, 
                              null, 
                              null);
                System.Diagnostics.Debug.WriteLine("Is proxy={0}",
                             RemotingServices.IsTransparentProxy(_loader)); 
                                 //writes false
                 _loader.Session = this;
                 return _loader;
            }
        }

This works fine. But I assume all the method calls on _loader instance will invoke in other domain (myDomain). But when I run following code, it still writes main app domain.

public void LoadModule(string moduleAssembly)
        {
            System.Diagnostics.Debug.WriteLine("Is proxy={0}", 
                     RemotingServices.IsTransparentProxy(this));
            System.Diagnostics.Debug.WriteLine(
                          AppDomain.CurrentDomain.FriendlyName);
            System.Diagnostics.Debug.WriteLine("-----------");
        }

Is it because of Unwrap()? Where I am doing wrong?

I understand AppDomain creates seperate memory. What I need is my main application runs, it loads modules in different AppDomain. Since main app also wants to watch some activity of modules and interfare with objects running in seperate domain, what is the best way to achieve it.

回答1:

If you want to actually run the code in the other assembly, you need to make your ModuleLoader class inherit from MarshalByRefObject. If you do that, CreateInstanceAndUnwrap() will actually return a proxy and the call will be executed in the other appdomain.

If you don't do that, and instead mark the class as Serializable (as an exception message suggests), CreateInstanceAndUnwrap() will create the object in the other appdomain, serialize it, transfer the serialized form to the original appdomain, deserialize it there and call the method on the deserialized instance.