0

It seems this question has been asked before, but none of the answers around here on StackOverlow actually solve my issue, though some answers say it should.

What I see, is when I call AppDomain.CreateInstanceFromAndUnwrap to load create a type in another AppDomain than the main AppDomain, the assembly that holds that type is also loaded in the main application domain and that is what I do not want.

I have the following code:

AppDomainSetup appDomainSetup = new AppDomainSetup();
appDomainSetup.ApplicationName = @"TestDomain";
appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
AppDomain testDomain = AppDomain.CreateDomain(appDomainSetup.ApplicationName, null, appDomainSetup);

object other = testDomain.CreateInstanceFromAndUnwrap(@"TestLib.dll", @"TestLib.Class1");

When I print the assemblies loaded in the main application domain before I call CreateInstanceFromAndUnwrap, the TestLib.dll is not loaded in the main application domain, while it is loaded in the main application domain right after this call!

Also changing the `CreateInstanceFromAndUnwrap call to:

byte[] assemblyBytes = File.ReadAllBytes(@".\TestLib.dll");
testDomain.Load(assemblyBytes);

will result in the TestLib.dll being loaded in both application domains.

What can I do to prevent the TestLib.dll to be loaded in the main application domain?

Marcel V.
  • 53
  • 9
  • What version of .NET? AppDomain behavior (and support for various scenarios) changed significantly in .NET Core (.NET 5 and beyond). – Jeroen Mostert Jan 17 '23 at 21:30
  • I'm 99% sure it is expected behavior for .Net 4.x and below (full framework). Start reading all articles on "implement add-ins with AppDomain" (or whatever search terms around AppDomains you like... Sample SO post - https://stackoverflow.com/questions/1137781/correct-way-to-load-assembly-find-class-and-call-run-method – Alexei Levenkov Jan 17 '23 at 23:29
  • Currently using .NET Framework 4.8.1. I will try another test with .NET 6 and see what happens. – Marcel V. Jan 19 '23 at 05:10
  • Hmm... I noticed that .NET5+ doesn't support AppDomains anymore, at least not multiple within 1 process and it now needs to be done using AssemblyLoadContexts. So I guess I need to dive into that when I later update to .NET6. Can anyone confirm this is expected behaviour for .NET 4.x? Especially since Microsoft says this is the way to load an assembly and unload it later. – Marcel V. Jan 20 '23 at 20:45

0 Answers0