How to pass an unknown type between two .NET AppDomains?

早过忘川 提交于 2019-11-30 10:06:05
cjk

I asked a related question a while back:

Would you say .Net remoting relies on tight coupling?

This fails because the CLR just has no hope of being able to find the assembly, you put it in an unfindable location. Trivially solve this by adding a reference to the assembly and setting its Copy Local property to True so that server.dll gets copied into your build directory. If you want to keep it where it is at then you'll have to implement AppDomain.AssemblyResolve to help the CLR finding it.

I think I have a solution thanks to current post, and this one and its accepted answer : AppDomain.Load() fails with FileNotFoundException

First thing, I think you should use an interface in place of a base class to be your handler. The interface should be declared on base class, and then you only use it.

Solution : create a concrete type in the shared assembly, which inherits from MarshalByRefObject, and implements your server interface. This concrete type is a proxy that can be serialized/deserialized between AppDomains because your main application knows its definition. You no longer need to inherit from MarshalByRefObject in your class ServerBase.

  // - MUST be serializable, and MUSNT'T use unknown types for main App
  [Serializable]
  public class Query 
  {
     ...
  }

  public interface IServerBase
   {  
       string Execute(Query q);
   }

  public abstract class ServerBase : IServerBase
  {
       public abstract string Execute(Query q);
  }

// Our CUSTOM PROXY: the concrete type which will be known from main App
[Serializable]
public class ServerBaseProxy : MarshalByRefObject, IServerBase
{
    private IServerBase _hostedServer;

    /// <summary>
    /// cstor with no parameters for deserialization
    /// </summary>
    public ServerBaseProxy ()
    {

    }

    /// <summary>
    /// Internal constructor to use when you write "new ServerBaseProxy"
    /// </summary>
    /// <param name="name"></param>
    public ServerBaseProxy(IServerBase hostedServer)
    {
        _hostedServer = hostedServer;
    }      

    public string Execute(Query q)
    {
        return(_hostedServer.Execute(q));
    }

}

Note: in order to send and receive data, each type declared in IServer must be serializable (for example: with [Serializable] attribute)

Then, you can use the method found in previous link "Loader class". Here is my modified Loader class which instanciate concrete type in shared assembly, and returns a Proxy for each Plugin:

  /// <summary>
/// Source: https://stackoverflow.com/questions/16367032/appdomain-load-fails-with-filenotfoundexception
/// </summary>
public class Loader : MarshalByRefObject
{

    /// <summary>
    /// Load plugins
    /// </summary>
    /// <param name="assemblyName"></param>
    /// <returns></returns>
    public IPlugin[] LoadPlugins(string assemblyPath)
    {
        List<PluginProxy> proxyList = new List<PluginProxy>(); // a proxy could be transfered outsite AppDomain, but not the plugin itself ! https://stackoverflow.com/questions/4185816/how-to-pass-an-unknown-type-between-two-net-appdomains

        var assemb = Assembly.LoadFrom(assemblyPath); // use Assembly.Load if you want to use an Assembly name and not a path

        var types = from type in assemb.GetTypes()
                    where typeof(IPlugin).IsAssignableFrom(type)
                    select type;

        var instances = types.Select(
            v => (IPlugin)Activator.CreateInstance(v)).ToArray();

        foreach (IPlugin instance in instances)
        {
            proxyList.Add(new PluginProxy(instance));
        }
        return (proxyList.ToArray());
    }

}

Then, in the master application, I also use the code of "dedpichto" and "James Thurley" to create AppDomain, instanciate and invoke Loader class. I am then able to use my Proxy as it was my plugin, because .NET creates a "transparent proxy" due to MarshalByRefObject :

   /// <see cref="https://stackoverflow.com/questions/4185816/how-to-pass-an-unknown-type-between-two-net-appdomains"/>
public class PlugInLoader
{       

    /// <summary>
    /// https://stackoverflow.com/questions/16367032/appdomain-load-fails-with-filenotfoundexception
    /// </summary>
    public void LoadPlugins(string pluginsDir)
    {
        // List all directories where plugins could be
        var privatePath = "";
        var paths = new List<string>();
        List<DirectoryInfo> dirs = new DirectoryInfo(pluginsDir).GetDirectories().ToList();
        dirs.Add(new DirectoryInfo(pluginsDir));
        foreach (DirectoryInfo d in dirs)
            privatePath += d.FullName + ";";
        if (privatePath.Length > 1) privatePath = privatePath.Substring(0, privatePath.Length - 1);

        // Create AppDomain !
        AppDomainSetup appDomainSetup = AppDomain.CurrentDomain.SetupInformation;
        appDomainSetup.PrivateBinPath = privatePath; 

        Evidence evidence = AppDomain.CurrentDomain.Evidence;
        AppDomain sandbox = AppDomain.CreateDomain("sandbox_" + Guid.NewGuid(), evidence, appDomainSetup);

        try
        {
            // Create an instance of "Loader" class of the shared assembly, that is referenced in current main App
            sandbox.Load(typeof(Loader).Assembly.FullName);

            Loader loader = (Loader)Activator.CreateInstance(
                sandbox,
                typeof(Loader).Assembly.FullName,
                typeof(Loader).FullName,
                false,
                BindingFlags.Public | BindingFlags.Instance,
                null,
                null,
                null,
                null).Unwrap();

            // Invoke loader in shared assembly to instanciate concrete types. As long as concrete types are unknown from here, they CANNOT be received by Serialization, so we use the concrete Proxy type.

            foreach (var d in dirs)
            {
                var files = d.GetFiles("*.dll");
                foreach (var f in files)
                {
                    // This array does not contains concrete real types, but concrete types of "my custom Proxy" which implements IPlugin. And here, we are outside their AppDomain, so "my custom Proxy" is under the form of a .NET "transparent proxy" (we can see in debug mode) generated my MarshalByRefObject.
                    IPlugin[] plugins = loader.LoadPlugins(f.FullName);
                    foreach (IPlugin plugin in plugins)
                    {
                        // The custom proxy methods can be invoked ! 
                        string n = plugin.Name.ToString();
                        PluginResult result = plugin.Execute(new PluginParameters(), new PluginQuery() { Arguments = "", Command = "ENUMERATE", QueryType = PluginQueryTypeEnum.Enumerate_Capabilities });
                        Debug.WriteLine(n);
                    }                    
                }
            }
        }
        finally
        {
            AppDomain.Unload(sandbox);
        }
  }
}

It's really hard to find out a working solution, but we finally can keep instances of custom proxies of our concrete types instanciated in another AppDomain and use them as if they was available in main application.

Hope this (huge answer) helps !

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