代码之家  ›  专栏  ›  技术社区  ›  Al Katawazi

在新AppDomain中加载程序集,而不在父AppDomain中加载它

  •  18
  • Al Katawazi  · 技术社区  · 16 年前

    string fileLocation = @"C:\Collector.dll";
    AppDomain domain = AppDomain.CreateDomain(fileLocation);
    domain.Load(@"Services.Collector");
    AppDomain.Unload(domain);
    

    顺便说一句,我也尝试了这个代码没有运气也

    string fileLocation = @"C:\Collector.dll";
    byte[] assemblyFileBuffer = File.ReadAllBytes(fileLocation);
    
    AppDomainSetup domainSetup = new AppDomainSetup();
    domainSetup.ApplicationBase = Environment.CurrentDirectory;
    domainSetup.ShadowCopyFiles = "true";
    domainSetup.CachePath = Environment.CurrentDirectory;
    AppDomain tempAppDomain = AppDomain.CreateDomain("Services.Collector", AppDomain.CurrentDomain.Evidence, domainSetup);
    
    //Load up the temp assembly and do stuff 
    Assembly projectAssembly = tempAppDomain.Load(assemblyFileBuffer);
    
    //Then I'm trying to clean up 
    AppDomain.Unload(tempAppDomain);
    tempAppDomain = null;
    File.Delete(fileLocation); 
    
    2 回复  |  直到 16 年前
        2
  •  4
  •   Ondrej Svejdar    10 年前

    这应该很简单:

    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);
        }
      }
    }