在New AppDomain中加载程序集而不将其加载到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); } } }