I had some problems figuring out a good title, but hopefully the code examples in this post are clear enough.
Is it possible, with the help of expression trees (or some other technique), to traverse the whole method "call stack"? Worded differently: When I get an expression tree from an Action-delegate, I would like to traverse inside the statements which happen inside the delegate.
I think it's best to move into examples as soon as possible... I have an abstract class called Command. Inside the Command is the following method:
protected void Run()
{
RunCommand (() => this.Execute());
}
Execute is an abstract method which is implement by my sub classes. Here's an example of one Execute-method:
protected override void Execute()
{
var data = new RegistrationData {HomeTown = "town"};
service.SendNewRegistration(data);
}
In my RunCommand-method I would like to get my hands on the statements inside the Execute-method. The method is defined as following:
protected void RunCommand(Expression<Action> expression)
{
// Is it possible to find out that we're calling SendNewRegistration
// of a service-instance in our expression?
expression.Compile().Invoke();
}
Before calling the Invoke, is it possible to find out what happens inside the sub classes Execute-method? What is declared, what methods are executed and what parameters are used?
I tried to extend the ExpressionVisitor to see what is happening and made it to log VisitMethodCall-executions:
protected override Expression VisitMethodCall(MethodCallExpression m)
{
Debug.WriteLine(m.Method.Name);
return m;
}
And the output was: Execute. So that didn't take me far. Is it somehow possible to the reach the statements inside the Execute-method?