0

Possible Duplicate:
Unloading the Assembly loaded with Assembly.LoadFrom()

I use custom AppDomain to load/unload assembly. But when assembly is unloaded I am able to see it under the AppDomain.CurrentDomain.

How it could be? Is this normal behavior or I am missing something?

Thank you for any clue!

 string assemblyPath = @"C:\MyFile.dll";
 var assemblyName = AssemblyName.GetAssemblyName(assemblyPath);

            var ads = new AppDomainSetup
                          {
                              ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, 
                              DisallowCodeDownload = true 
                          };

            AppDomain newDomainName = AppDomain.CreateDomain("newDomainName", null, ads);
              try
              {
                  Assembly testLibrary = newDomainName.Load(assemblyName);

                  var c1 = AppDomain.CurrentDomain.GetAssemblies();

                  var c2 = newDomainName.GetAssemblies();
              }
              finally
              {
                  AppDomain.Unload(newDomainName);

                  var c3 = AppDomain.CurrentDomain.GetAssemblies();

                  // The assembly is still visible here!!!
              }
Community
  • 1
  • 1
NoWar
  • 36,338
  • 80
  • 323
  • 498
  • @asawyer No it is not a duplicated question I use a new AppDomain to keep there loaded assembly. – NoWar Sep 17 '12 at 13:29

2 Answers2

4

You are calling the Load() method of an AppDomain, which according to the documentation: "should be used only to load an assembly into the current application domain. This method is provided as a convenience for interoperability callers who cannot call the static Assembly.Load method. To load assemblies into other application domains, use a method such as CreateInstanceAndUnwrap."

In other words, you're loading the assembly into the primary AppDomain because you're calling Load() from the primary AppDomain (even though you're using calling it on an instance of your secondary AppDomain), and this is why it is appearing even after you unload your secondary AppDomain.

As indicated in the extract from the documentation above, you probably want to use AppDomain.CreateInstanceAndUnwrap.

Iridium
  • 23,323
  • 6
  • 52
  • 74
2

You can't remove a loaded assembly from an app domain.

http://blogs.msdn.com/b/jasonz/archive/2004/05/31/145105.aspx

http://msdn.microsoft.com/en-us/library/ms173101(v=vs.80).aspx

There is no way to unload an individual assembly without unloading all of the application domains that contain it. Even if the assembly goes out of scope, the actual assembly file will remain loaded until all application domains that contain it are unloaded.

http://blogs.msdn.com/b/suzcook/archive/2003/07/08/unloading-an-assembly.aspx

There's no way to unload an individual assembly without unloading all of the appdomains containing it.

asawyer
  • 17,642
  • 8
  • 59
  • 87