I want to inject code into a external method, without editing the source code. I can already replace the current method to reference to my own method, because of Dynamically replace the contents of a C# method?.
I still need to able to modify a external method body at runtime, which means to be able to inject code before the method call and after the method call.
I can't manually call this method i want to modify. is a service that runs itself.
I have tried:
- Reflection.Emit -> but this creates a new method which is not referenced.
- Marshall ->
Marshal.GetFunctionPointerForDelegate
, and then replace the method to after that call the marshalled function -> does not work as the replace is a pointer and the marhal changes the pointer.
Situation:
class Program
{
static void Main(string[] args)
{
var oldMethod = typeof(InstanceClassA).GetMethod("OldMethod", BindingFlags.Instance | BindingFlags.Public);
var beforeMethod = typeof(InstanceClassA).GetMethod("BeforeMethod", BindingFlags.Instance | BindingFlags.Public);
oldMethod.Before(() => Console.WriteLine("Called Before"));
oldMethod.Before(() => beforeMethod);
//This is *TESTING* only as I can't manually call the method i want to inject.
var instance = new InstanceClassA();
//Should now call the beforeMethod and the called before
instance.OldMethod("With Before");
//Should call the after method
Console.ReadLine();
}
}
public static class MethodInfoUtils
{
//Will *NOT* allow return values as this should return oldMethod return value
//Will allow Actions and another MethodInfo
public static void Before(this MethodInfo method)
{
// Code to inject code before calling the external method
}
//Will *NOT* allow return values as this should return oldMethod return value
//Will allow Actions and another MethodInfo
public static void After(this MethodInfo method)
{
// Code to inject code after calling the external method
}
}
public class InstanceClassA
{
public bool OldMethod(string message)
{
Console.WriteLine(message);
return true;
}
//message param is equal to the oldMethod param as it is called before the oldMethod is called
public void BeforeMethod(string message)
{
Console.WriteLine("test");
}
}