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?

4
  • What version of .NET? AppDomain behavior (and support for various scenarios) changed significantly in .NET Core (.NET 5 and beyond). Commented Jan 17, 2023 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 - stackoverflow.com/questions/1137781/… Commented Jan 17, 2023 at 23:29
  • Currently using .NET Framework 4.8.1. I will try another test with .NET 6 and see what happens. Commented Jan 19, 2023 at 5: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. Commented Jan 20, 2023 at 20:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.