title: Serialize a method invocation to JSON then deserialize and call the method
body: <p>I need to find a way to serialize a method call and it's associated parameter.  This is because we'll be passing payloads onto a queue (like MSMQ) and then later on a process will pick up the message and need to deserialize the payload and call the method required.</p>
  
  <p>Both sides of the queue use the same C# library, but one is inside a Web context and the other is inside a batch process / console app.</p>
  
  <p>I have demonstrated below what I'd like to do, however, I realise it may not be possible.  I know I could always encapsulate the meta data of what target method call and the have some huge switch statement that maps a parameter/payload to a method, however, it would be very cool and succinct if I could call any method I want (it doesn't matter whether it's static).</p>
  
  <pre><code>namespace SerializableMethodCalls
  {
  public class DTO
  {
      public string MyData { get; set; }
      public int AnInteger { get; set; }
  }
  
  public class DTO2
  {
      public string MyData2 { get; set; }
      public int AnInteger2 { get; set; }
  }
  
  class Program
  {
      private static Queue&lt;string&gt; _queue = new Queue&lt;string&gt;();
  
      static void Main(string[] args)
      {
          DTO payload = new DTO
          {
              AnInteger = 45678,
              MyData = "Test"
          };
  
          DTO2 payload2 = new DTO2
          {
              AnInteger2 = 534653,
              MyData2 = "test2"
          };
  
          DoSomething(payload);
          DoSomething(payload2);
  
  
  
          _queue.Enqueue(Serialize(DoSomething, payload));
  
          while (_queue.Count &gt; 0)
          {
              var message = _queue.Dequeue();
              DeserializeAndCallMethod(message);
          }
  
      }
  
      private static void DeserializeAndCallMethod(string message)
      {
          // somehow deserialize the method invocation and then call the method with the serialized payload!
      }
  
      public static void DoSomething(DTO2 payload2)
      {
          Console.WriteLine("Done2! {0}, {1}", payload2.AnInteger2, payload2.MyData2);
      }
  
      public static void DoSomething(DTO dto)
      {
          Console.WriteLine("Done! {0}, {1}", dto.AnInteger, dto.MyData);
      }
  
      public static string Serialize(Method method, object parameter)
      {
          // somehow serialize a method call!?
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>I'd be interested in hearing your thoughts</p>
  
  <p>Many thanks</p>
  
  <p>Kris</p>