Skip to content

Instantly share code, notes, and snippets.

@mgroves
Created August 5, 2012 15:31
Show Gist options
  • Select an option

  • Save mgroves/3265408 to your computer and use it in GitHub Desktop.

Select an option

Save mgroves/3265408 to your computer and use it in GitHub Desktop.
Using C#'s dynamic to create a DynamicProxy
// from: http://weblogs.asp.net/lichen/archive/2012/08/03/gave-a-presentation-on-c-dynamic-and-dynamic-language-runtime-dlr-at-socal-net-user-group-meeting.aspx
// pros: no requirement for members to be virtual, no need for a 3rd party framework
// cons: loss of static typing benefits (i.e. intellisense & compile time checking), not practical for IoC
class Program
{
static void Main(string[] args)
{
dynamic myObj = new DynamicProxy(new MyClass());
myObj.Foo();
}
}
public class MyClass
{
public void Foo()
{
Console.WriteLine("foo");
}
}
public class DynamicProxy : DynamicObject
{
readonly object _target;
public DynamicProxy(object target)
{
_target = target;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
Console.WriteLine("before invoking " + binder.Name);
result = _target.GetType().InvokeMember(binder.Name, BindingFlags.InvokeMethod, null, _target, args);
Console.WriteLine("after invoking " + binder.Name);
return true;
}
}
@zhuchunqing
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment