Using DynamicObject (IDynamicMetaObjectProvider) as a component of a static type leads to infinite loop

前端 未结 2 1289
死守一世寂寞
死守一世寂寞 2021-01-31 23:49

I\'m trying to create a dynamic object that can be used as a component of a static object. Here is a contrived example of what I\'m trying to accomplish.

Here is the dy

2条回答
  •  深忆病人
    2021-02-01 00:22

    I think the problem is that the Expression parameter passed to GetMetaObject represents the target of the dynamic invocation (i.e. the current object). You are passing the outer object to the call on component.GetMetaObject, so the returned meta object is trying to resolve the call to AMethod on the outer object instead of itself, hence the infinite loop.

    You can create your own meta object which delegates to the inner component when binding member invocations:

    public class AStaticComponent : VendorLibraryClass, IDynamicMetaObjectProvider
    {
        IDynamicMetaObjectProvider component = new DynamicComponent();
    
        public DynamicMetaObject GetMetaObject(Expression parameter)
        {
            return new DelegatingMetaObject(component, parameter, BindingRestrictions.GetTypeRestriction(parameter, this.GetType()), this);
        }
    
        private class DelegatingMetaObject : DynamicMetaObject
        {
            private readonly IDynamicMetaObjectProvider innerProvider;
    
            public DelegatingMetaObject(IDynamicMetaObjectProvider innerProvider, Expression expr, BindingRestrictions restrictions)
                : base(expr, restrictions)
            {
                this.innerProvider = innerProvider;
            }
    
            public DelegatingMetaObject(IDynamicMetaObjectProvider innerProvider, Expression expr, BindingRestrictions restrictions, object value)
                : base(expr, restrictions, value)
            {
                this.innerProvider = innerProvider;
            }
    
            public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
            {
                var innerMetaObject = innerProvider.GetMetaObject(Expression.Constant(innerProvider));
                return innerMetaObject.BindInvokeMember(binder, args);
            }
        }
    }
    

提交回复
热议问题