简体   繁体   English

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

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

I am attempting to load a dll into a console app and then unload it and delete the file completely. 我试图将一个DLL加载到控制台应用程序,然后卸载它并完全删除该文件。 The problem I am having is that the act of loading the dll in its own AppDomain creates a reference in the Parent AppDomain thus not allowing me to destroy the dll file unless I totally shut down the program. 我遇到的问题是,在自己的AppDomain中加载dll的行为会在Parent AppDomain中创建一个引用,因此不允许我销毁dll文件,除非我完全关闭程序。 Any thoughts on making this code work? 有关使此代码有效的任何想法?

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

BTW I have also tried this code with no luck either 顺便说一下,我也尝试过这段代码而且没有运气

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

OK so I solved my own issue here. 好的,所以我在这里解决了自己的问题。 Apparently if you call AppDomain.Load it will register it with your parent AppDomain. 显然,如果你调用AppDomain.Load,它会将它注册到你的父AppDomain。 So simply enough the answer is not to reference it at all. 如此简单,答案就是根本不参考它。 This is the link to a site that shows how to set this up properly. 这是指向如何正确设置此网站的网站的链接。

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

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

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

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