How to load a .NET assembly for reflection operations and subsequently unload it?

Drew Noakes picture Drew Noakes · Oct 22, 2008 · Viewed 15.9k times · Source

I'm writing a tool to report information about .NET applications deployed across environments and regions within my client's systems.

I'd like to read the values of assembly attributes in these assemblies.

This can be achieved using Assembly.ReflectionOnlyLoad, however even this approach keeps the assembly loaded. The issue here is that I cannot load two assemblies that have the same name from different paths, so naturally I can't compare the same application deployed in different systems.

At this point I'm assuming the solution will involve using temporary AppDomains.

Can someone detail how to load an assembly into another AppDomain, read the attributes from it and then unload the AppDomain?

This needs to work for assemblies on the file system as well as those at URL addresses.

Answer

Tamas Czinege picture Tamas Czinege · Oct 22, 2008

From the MSDN documentation of System.Reflection.Assembly.ReflectionOnlyLoad (String) :

The reflection-only context is no different from other contexts. Assemblies that are loaded into the context can be unloaded only by unloading the application domain.

So, I am afraid the only way to unload an assembly is unloading the application domain. To create a new AppDomain and load assemblies into it:

public void TempLoadAssembly()
{
    AppDomain tempDomain = AppDomain.CreateDomain("TemporaryAppDomain");
    tempDomain.DoCallBack(LoaderCallback);
    AppDomain.Unload(tempDomain);
}

private void LoaderCallback()
{
    Assembly.ReflectionOnlyLoad("YourAssembly");
    // Do your stuff here
}