title: Dynamic IL method causes "Operation could destabilize the runtime"
body: <blockquote>
    <p>System.Security.VerificationException:
    Operation could destabilize the
    runtime.
           at Connance.CommunicatorApi.ReportApiClient.AcknowledgeRecallsAsyncDynamicHandler(Object
    , AcknowledgeRecallsCompletedEventArgs
    )</p>
  </blockquote>
  
  <p>That's the error I'm getting. What I'm trying to do (background) is create a global event handler for a class of methods. I'm working with a Static Proxy in WCF and I need to create a layer which tracks all the calls and returns to all of the WCF web methods. Unfortunately, WCF strongly types the "Completed" events' EventArgs, making it nearly impossible.</p>
  
  <p>I decided to try something. If an event is <code>EventHandler&lt;SomeSpecificEventArgs&gt;</code>, I can still register a method of signature <code>void Method(object, object)</code> to handle the event. Great. So I set off to create a <code>DynamicMethod</code> which would call my <strong>global</strong> handler, and register it to each event.</p>
  
  <p>I tried two ways:</p>
  
  <blockquote>
    <p>1) DynamicMethod is of type void
    (object, object)</p>
    
    <p>2) of type void (object,
    SomeSpecificEventArgs)  -- I use a
    generic method for this to get the
    type.</p>
  </blockquote>
  
  <p>Only, when I try to invoke the method, either manually or for the event, I get the above exception.</p>
  
  <p>Here's my code: </p>
  
  <pre><code>    // The handler for all callbacks.
  // in the example it does nothing.
  public void Handler(object sender, object e)
  {
      dynamic evtArgs = e;
      object userState = evtArgs.UserState;
  }
  
  private string GetIdentifier(Delegate d)
  {
      return string.Concat(d.Method.DeclaringType, '.', d.Method.Name);
  }
  
  // Method to register an event handler
  public void Register&lt;T&gt; (Delegate o) where T : EventArgs
  {
      // get some info
      /* snip. code to get method name, and calculate name of event */
  
      var eventInst = ownerType.GetEvent(eventName);
  
      // The following works, for example:
      // someObj.MethodCompleted += Handler;
      // even though MethodCompleted is an event of type EventHandler&lt;SomeSpecialEventArgs&gt;
  
      // get the actual type of handler
      var handlerType = eventInst.EventHandlerType;
      EventHandler evtHandler = new EventHandler(Handler);    
  
      DynamicMethod dm = new DynamicMethod(
          GetIdentifier(o) + "DynamicHandler", // set the name
          typeof(void),                        // return void
          new[] { typeof(object), typeof(T) });// params object and type of event args
  
      ILGenerator gen = dm.GetILGenerator();
  
      gen.Emit(OpCodes.Ldarg_0); // load first arg to stack for calling
      gen.Emit(OpCodes.Ldarg_2); // load second arg to stack for calling
  
      gen.Emit(OpCodes.Call, evtHandler.Method); // call method
  
      gen.Emit(OpCodes.Ret); // return
  
      // this is the final delegate
      var superdlg = dm.CreateDelegate(handlerType);
  
      // the problem beings here:
      // when the event is raised and the delegate is invoked
      // of if I dynamicInvoke it, I get the error
      eventInst.AddEventHandler(ownerInst, superdlg);
  }
  </code></pre>
  
  <p>edit:
  I see. It turns out I have another issue. I'm working in Silverlight. I managed to reproduce my scenario in a separate project and I got it working by using the overload of <code>DynamicMethod</code> which allows you to set an owner. I then specify </p>
  
  <p><code>DynamicMethod dm = new DynamicMethod("TestMethod2", typeof(void), new[] { typeof(MyClass), typeof(string), typeof(string) }, typeof(MyClass));</code>, </p>
  
  <p>and use <code>ldarg.0</code>, <code>ldarg.1</code>, and <code>ldarg.2</code>. But this is a security critical constructor and won't run on silverlight. I'm just not sure how I need to set it up then. Do I make the <code>Handler</code> public static and load args 0-1? I end up getting an error like this: </p>
  
  <blockquote>
    <p>Attempt by method
    'DynamicClass.TestMethod2(System.String,
    System.String)' to access method
    'dynamicass.MyClass.Handler(System.String,
    System.String)' failed."}</p>
  </blockquote>