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

时间:2010-04-26 16:30:43

标签: c# .net console-application appdomain

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

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

BTW我也尝试过这段代码而没有运气

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 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:4)

这应该很容易:

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