I was looking at a way to implement a class Proxy in .NET (Core) and found out there is actually an implementation in the framework called DispatchProxy (source code). When I looked at the source code, it is actually implemented here at DispatchProxyGenerator.
I am interested in knowing how it is implemented. However I reach an impasse here as my knowledge is limited. I cannot really understand how it works. Can someone enlighten me?
My best guess from the code is it try to create at runtime the type members using System.Reflection
and emits some IL code, is it correct? Suppose I want to create a very simple DispatchProxy implementation, can I simply use something like DynamicObject
and returns a delegate instead?
private void Complete()
{
Type[] args = new Type[_fields.Count];
for (int i = 0; i < args.Length; i++)
{
args[i] = _fields[i].FieldType;
}
ConstructorBuilder cb = _tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, args);
ILGenerator il = cb.GetILGenerator();
// chained ctor call
ConstructorInfo baseCtor = _proxyBaseType.GetTypeInfo().DeclaredConstructors.SingleOrDefault(c => c.IsPublic && c.GetParameters().Length == 0);
Debug.Assert(baseCtor != null);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseCtor);
// store all the fields
for (int i = 0; i < args.Length; i++)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg, i + 1);
il.Emit(OpCodes.Stfld, _fields[i]);
}
il.Emit(OpCodes.Ret);
}