title: Making a lambda expression to call a method from a generic class
body: <p>I have these simple interface:</p>
  
  <pre><code>public interface IQuery&lt;TResult&gt; { }
  
  public interface IQueryHandler&lt;in TQuery, out TResult&gt; 
      where TQuery : IQuery&lt;TResult&gt; {
      TResult Handle(TQuery query);
  }
  </code></pre>
  
  <p>And there are some implementation of them. I'm trying to create an expression-tree to call <code>Handle</code> method on a specified handler. I mean:</p>
  
  <pre><code>var query = new MyQuery(); // which MyQuery implements IQuery&lt;int&gt;
  object handler = _someServiceProvider
      .Get&lt;IQueryHandler&lt;MyQuery, int&gt;&gt;();
  </code></pre>
  
  <p>Also, there is a <code>MyQueryHandler</code>:</p>
  
  <pre><code>public class MyQueryHandler : IQueryHandler&lt;MyQuery, int&gt; {
      public int Handle(MyQuery query) { return 20; }
  }
  </code></pre>
  
  <p>Now, I'm trying to create a <code>Func&lt;object, MyQuery, int&gt;</code> to call like this:</p>
  
  <pre><code>var func = GetMethod&lt;MyQuery, int&gt;(handler);
  var result = func(handler, query);
  </code></pre>
  
  <p>And here is my <code>GetMethod</code> implementation:</p>
  
  <pre><code>    private Func&lt;object, TQuery, TResult&gt; GetMethod&lt;TQuery, TResult&gt;(object obj)
          where TQuery : IQuery&lt;TResult&gt; {
  
          var methodInfo = obj.GetType().GetMethod(nameof(IQueryHandler&lt;TQuery, TResult&gt;.Handle));
  
          var insExp = Expression.Parameter(typeof(object), "ins");
  
          var inputExp = Expression.Parameter(typeof(TQuery), "query");
  
          var instanceExp = Expression.Variable(obj.GetType(), "instance");
  
          var assExp = Expression.Assign(instanceExp, Expression.Convert(insExp, obj.GetType()));
  
          var castExp = Expression.Convert(inputExp, methodInfo.GetParameters()[0].ParameterType);
  
          var callExp = Expression.Call(instanceExp, methodInfo, castExp);
  
          var blockExp = Expression.Block(new Expression[] {
              insExp,
              inputExp,
              instanceExp,
              assExp,
              castExp,
              callExp
          });
  
          var func =
              Expression.Lambda&lt;Func&lt;object, TQuery, TResult&gt;&gt;(
                  blockExp,
                  insExp,
                  inputExp).Compile();
          return func;
      }
  </code></pre>
  
  <p>But, when I try to compile <code>Lambda</code>, I get this error:</p>
  
  <blockquote>
    <p>An exception of type 'System.InvalidOperationException' occurred in
    System.Core.dll but was not handled in user code</p>
    
    <p>Additional information: variable 'instance' of type
    'Namespace.MyQueryHandler' referenced from scope '', but it is not
    defined</p>
  </blockquote>
  
  <p>Where am I wrong? What I missed? Do you have any idea? Thanks in advance.</p>