I have a .NET Framework console app. It needs to dynamically load an assembly, create an object from a class defined in this assembly, invoke it's methods using reflection, then dynamically unload the assembly so that the DLL can be deleted or moved.
For this, I had to create a separate app domain and load the assembly into that app domain:
Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
AppDomain appDomain = AppDomain.CreateDomain("mydomain", evidence, setup);
var myObj = (OrigDllAssembly)origDllAppDomain.AppDomain.CreateInstanceFrom(
assemblyFile: myDllLocation,
typeName: typeOfMyAssembly.FullName,
ignoreCase: false,
bindingAttr: 0,
binder: null,
args: new object[] { constructorParam },
culture: null,
activationAttributes: null).Unwrap();
When I need to unload the assembly, I unload the app domain:
AppDomain.Unload(appDomain);
It all works well and I was able to invoke methods on "myObj", except that the assembly expires after precisely 5 minutes. After this, if I try to access anything of this assembly, I got this exception:
Object '/51f0cea8_a5a5_40ec_a225_15a666329eea/iemetjgnsvxlskiviwzkcjda_2.rem' has been disconnected or does not exist at the server.
I am sure that I have never accidentally unloaded the app domain when I didn't mean to, because I put a breakpoint in the "app domain unloaded" event handler and this event was ever fired unless I deliberately unloaded the app domain.
How do I prevent this auto expiring from happening, so that the assembly stays alive forever until I deliberately unload the app domain?