The scenario is such that you load an assembly and after some time you need to unload it. Assemblies for themselves are not unloadable, thus you need an application domain to isolate the assemblies. AppDomains can be unloaded.
If you need to load an assembly by file name you need the method Assembly.LoadFrom, which has no equivalent in AppDomain. Therefore a proxy must be used, a minimal proxy could look like:
public class LoadProxy : MarshalByRefObject
{
public void LoadAssembly(string assFile)
{
Assembly asm = Assembly.LoadFrom(assFile);
// ....
}
// ...
}
The Proxy inherits MarshalByRefObject, thus it will stay in the unloadable domain. On the permanent side we just use a “stub”.
The code on the permanent side could look like:
AppDomain ad = AppDomain.CreateDomain("Temporary Assembly Domain");
LoadProxy lp = (LoadProxy) ad.CreateInstanceAndUnwrap("Name of the assembly to load", "Full qualified classname of the class to load");
lp.LoadAssembly(assFile);
// ...
AppDomain.Unload(ad);
Note: The proxy may reside in a seperate assembly, but it might be possible to have it in the same assembly as the permanent code.
Pro for single assembly: easy deployment
Pro for multiple assemblies: works for sure, less unused code to load in the unloadable domain.