2

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);
        }
Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • So ILGenerator can be used to create method implementations, but I'm not sure what you are trying to do or which problem you are hitting. Using these types require knowledge of .NET internals and the intermediate language (IL) and I'm not sure which part of all the techniques involved you are asking about specifically – Martin Ullrich Mar 20 '19 at 20:16
  • Thanks. Yeah that's where I am stuck. I do not know much about .NET internals. I guess this is where I cannot get deeper without getting to know IL first? – Luke Vo Mar 20 '19 at 20:22
  • 1
    Looks like it. And you should not feel bad about it, it is not easy to understand / has a steep learning curve. – Martin Ullrich Mar 20 '19 at 21:40

0 Answers0