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

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
}

Leave a Comment