CreateInstanceAndUnwrap and Domain

拥有回忆 提交于 2019-12-18 15:34:45

问题


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.



来源:https://stackoverflow.com/questions/7044971/createinstanceandunwrap-and-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!