using System;
using Castle.DynamicProxy;
using Castle.Core.Interceptor;
namespace DynamicDuckTypeing
{
class Generator
{
static readonly ProxyGenerator _generator = new ProxyGenerator();
internal static object GenerateProxy(Type type, DynamicWrapper dynamicWrapper)
{
return _generator.CreateInterfaceProxyWithoutTarget(type, new Interceptor(dynamicWrapper));
}
}
class Interceptor : IInterceptor
{
DynamicWrapper _wrapper;
public Interceptor(DynamicWrapper wrapper)
{
_wrapper = wrapper;
}
public void Intercept(IInvocation invocation)
{
object result;
//property access will be converted to get_XXX and set_XXX, use String.Substring(4) to get the real proertyName
if (invocation.Method.Name.StartsWith("get_"))
{
invocation.ReturnValue = _wrapper.TryGetMember(invocation.Method.Name.Substring(4), out result);
invocation.ReturnValue = result;
}
else if (invocation.Method.Name.StartsWith("set_"))
{
_wrapper.TrySetMember(invocation.Method.Name.Substring(4), invocation.Arguments[0]);
}
else
{
_wrapper.TryInvokeMember(invocation.Method.Name, invocation.Arguments, out result);
invocation.ReturnValue = result;
}
}
}
}