This post originated from an RSS feed registered with .NET Buzz
by Ranjan Sakalley.
Original Post: Using AppDomain.Unload II
Feed Title: Ranjan Sakalley
Feed URL: /error.htm?aspxerrorpath=/blogs/ranjan.sakalley/rss.aspx
Feed Description: (the life and times of a mock object)
There were a few mistakes in the last post on the AppDomain.Unload solution (thanks Manoj for pointing out) (John Papa wanted to know why I did not use LoadFile, thanks John, now I know should have written that MarshalByRef, just forgot it completely.) And sorry for this delayed update, damn weekend.
First of all,I missed to mention the MarshalByRef derivation for the AssemblyLoader. This is essential because the Dispatch should be made to the secondary AppDomain, and if the AssemblyLoader is not a MarshalByRef object, the dynamic assembly (Tested there) will be loaded in the primary AppDomain, and therefore, the latest version will not run.So if you have just copied and pasted the code somewhere, it might not work. Just inherit MarshalByRef for the AssemblyLoader and it should work. The update is in red.
[Serializable] public class AssemblyLoader : MarshalByRef { public void LoadAndRun() {
Second thing, there is a workaround, if you do not want the calls to be dispatched to the secondary AppDomain. You can use the following -
[Serializable] public class AssemblyLoader { public void Load() { FileStream _fileStream = File.OpenRead("Tested.dll"); byte[] _assemblyAsByteArray = new byte[_fileStream.Length]; _fileStream.Read(_assemblyAsByteArray,0,(int)_fileStream.Length); _fileStream.Close(); Assembly _assembly = Assembly.Load(_assemblyAsByteArray); Type _type =_assembly.GetTypes()[0]; MethodInfo _method =_type.GetMethod("Test"); _method.Invoke(Activator.CreateInstance(_type),null);
}
}
That is, do not inherit the AssemblyLoader from MarshalByRef, and Load the assembly as a byte array. This loads the latest version. The good part here is that there are no calls dispatched on the secondary appdomain, so it should be faster. The bad break is, there is an upfront overload of File IO. And yes, I do not know if this is supported or not.