title: AppDomain.CreateInstanceFromAndUnwrap - Unable to cast transparent proxy
body: <p>I'm writing a .NET library to inject managed DLLs into external processes. My current approach is:</p>
  
  <ol>
  <li>Use <code>CreateRemoteThread</code> to force the target process to call <code>LoadLibrary</code> on an unmanaged bootstrap DLL. From this point we're executing code in the target process.</li>
  <li>My bootstrap DLL then creates an instance of the CLR and calls <code>ExecuteInDefaultAppDomain</code> on it, which executes a method in a managed helper DLL.</li>
  <li>This method creates a new AppDomain and calls <code>AppDomain.CreateInstanceFromAndUnwrap</code> to pass execution into my payload DLL, casting the result as an <code>IInjectionPayload</code>.</li>
  <li>The idea is that my payload DLL exposes a class which implements <code>IInjectionPayload</code>, so the helper DLL can simply call <code>payload.Run()</code>.</li>
  </ol>
  
  <p>I'm doing it this way so that the payload code can be completely unloaded by simply calling <code>AppDomain.Unload</code> (after signalling it to clean up).</p>
  
  <p>This approach works - the class in my payload DLL is getting instantiated in the target process, so code <em>can</em> be executed - but I can't cast the object returned by <code>CreateInstanceFromAndUnwrap</code> to an <code>IInjectionPayload</code>; it throws the following exception:</p>
  
  <blockquote>
    <p>Unable to cast transparent proxy to type 'blah.Blah.IInjectionPayload'.</p>
  </blockquote>
  
  <p>I've tried using <code>CreateInstanceAndUnwrap</code>, and <code>Activator.CreateInstanceFrom</code> followed by <code>Object.Unwrap</code>, but both of these methods also cause the same exception to be thrown.</p>
  
  <p>The signature of my payload class is:</p>
  
  <blockquote>
    <p><code>public class Program : MarshalByRefObject, IInjectionPayload</code></p>
  </blockquote>
  
  <p>I'm stumped because the payload DLL is definitely getting loaded and the class is being instantiated, as intended. Any help would be much appreciated.</p>