Reflection without locking

Every now and then, you need to use reflection. And usually – at least for me that is – you need to change the assembly you are reflecting. So, this is what happens:

  • you’re running application A;
  • have it load your assembly;
  • test what you need to test and find something needs to change in the assembly;
  • make the change, and build it;
  • build FAILS. ouch. Wazzup?
  • The DLL is still locked by Application A so can’t be overwritten;
  • Stop Application A;
  • Build assembly again;
  • Start application A;
  • Get to the point where you left it and reload the assembly.

Dang, that’s awful. Even more afwful, is the fact that there’s no way to unload an assembly from a running AppDomain. Luckily, there’s a way to prevent the assem,bly from being locked in the first place. That way you’ll be able to rebuild the assembly after all. In stead of loading the assembly using Assembly.LoadFile();

You can read the .dll file itself into a bytearray and load the assembly from that. This way, the file itself will not be locked and can be rebuild over and over again:
FileStream fs = File.OpenRead(fileName);
Byte[] bytes=new byte[fs.Length];
fs.Read(bytes, 0,(int)fs.Length);
interfaceAssembly = Assembly.Load(bytes);

Off course, if you want the application to actually use the newly built assembly, you’ll need to have it reload the assembly again…

Fun Stuff.