Exemple #1
0
        public static DestinationMemberSetter <TContext> CreateConstructingAccessorChain <TContext>(this IEnumerable <MemberInfo> members,
                                                                                                    IResourceMapper <TContext> mapper)
        {
            if (members.Count() < 1)
            {
                throw new ArgumentException("Collection must have at least one member", "members");
            }
            var accessors = members.Select(prop => prop.GetAccessor()).ToList();

            accessors.Reverse();
            DestinationMemberSetter <TContext> setter = null;

            foreach (var propertyAccessor in accessors)
            {
                var accessor = propertyAccessor;
                // a = (((b = ((c = (d = 4)))) : Given a, get or create b and set this equal to c...
                if (setter == null)
                {
                    setter = (target, value, context) =>
                    {
                        accessor.Set(target, value);
                        return(target);
                    };
                }
                else
                {
                    var localSetter = setter;
                    setter = (target, value, context) =>
                    {
                        var destination = accessor.Get(target);
                        if (destination == null)
                        {
                            destination = mapper.ConstructOrThrow(accessor.MemberType);
                            accessor.Set(target, destination);
                        }
                        return(localSetter(destination, value, context));
                    };
                }
            }
            return(setter);
        }