Loading/Unloading assembly in different AppDomain

后端 未结 3 1465
忘掉有多难
忘掉有多难 2020-12-04 15:52

I need to execute a method in an assembly loaded during runtime. Now I want to unload those loaded assemblies after the method call. I know that I need a new AppDomain so I

相关标签:
3条回答
  • 2020-12-04 16:36

    Take a look into this previous answer: How to load an assembly into different AppDomain on Windows Mobile (.NET CF) ?. That answer creates a proxy class which runs into new AppDomain context so, there, you can have full control of your initialization.

    You could to create a Start() method into ServiceApplicationProxy class and just call it normally from your hoster with a proxy.Start().

    0 讨论(0)
  • 2020-12-04 16:39

    Try this:

    namespace SeperateAppDomainTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                LoadAssembly();
            }
    
            public static void LoadAssembly()
            {
                string pathToDll = Assembly.GetExecutingAssembly().CodeBase;
                AppDomainSetup domainSetup = new AppDomainSetup { PrivateBinPath = pathToDll };
                var newDomain = AppDomain.CreateDomain("FooBar", null, domainSetup);
                ProxyClass c = (ProxyClass)(newDomain.CreateInstanceFromAndUnwrap(pathToDll, typeof(ProxyClass).FullName));
                Console.WriteLine(c == null);
    
                Console.ReadKey(true);
            }
        }
    
        public class ProxyClass : MarshalByRefObject { }
    
    0 讨论(0)
  • 2020-12-04 16:45

    https://msdn.microsoft.com/en-us/library/3c4f1xde%28v=vs.110%29.aspx

    specifies that

    typeName Type: System.String

    The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the Type.FullName
    

    property.

    So try calling with Fully qualified name, instead of using typeof(InstanceProxy).ToString() use string/text "<<Namespace>>.InstanceProxy"

    as below

    InstanceProxy proxy = domain.CreateInstanceAndUnwrap(path, "<<Namespace>>.InstanceProxy") as InstanceProxy;
    
    0 讨论(0)
提交回复
热议问题