Load Assembly in New AppDomain without loading it in Parent AppDomain

后端 未结 2 1193
你的背包
你的背包 2020-12-25 14:15

I am attempting to load a dll into a console app and then unload it and delete the file completely. The problem I am having is that the act of loading the dll in its own App

2条回答
  •  一整个雨季
    2020-12-25 14:48

    This should be easy enough:

    namespace Parent {
      public class Constants
      {
        // adjust
        public const string LIB_PATH = @"C:\Collector.dll";
      }
    
      public interface ILoader
      {
        string Execute();
      }
    
      public class Loader : MarshalByRefObject, ILoader
      {
        public string Execute()
        {
            var assembly = Assembly.LoadFile(Constants.LIB_PATH);
            return assembly.FullName;
        }
      }
    
      class Program
      {
        static void Main(string[] args)
        {
          var domain = AppDomain.CreateDomain("child");
          var loader = (ILoader)domain.CreateInstanceAndUnwrap(typeof(Loader).Assembly.FullName, typeof(Loader).FullName);
          Console.Out.WriteLine(loader.Execute());
          AppDomain.Unload(domain);
          File.Delete(Constants.LIB_PATH);
        }
      }
    }
    

提交回复
热议问题