繁体   English   中英

在New AppDomain中加载程序集而不将其加载到Parent AppDomain中

[英]Load Assembly in New AppDomain without loading it in Parent AppDomain

我试图将一个DLL加载到控制台应用程序,然后卸载它并完全删除该文件。 我遇到的问题是,在自己的AppDomain中加载dll的行为会在Parent AppDomain中创建一个引用,因此不允许我销毁dll文件,除非我完全关闭程序。 有关使此代码有效的任何想法?

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

好的,所以我在这里解决了自己的问题。 显然,如果你调用AppDomain.Load,它会将它注册到你的父AppDomain。 如此简单,答案就是根本不参考它。 这是指向如何正确设置此网站的网站的链接。

https://bookie.io/bmark/readable/9503538d6bab80

这应该很容易:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM