Exemplo n.º 1
0
    private static string?DisplayNameResolver(Type type, MemberInfo memberInfo, LambdaExpression expression)
    {
        if (memberInfo == null)
        {
            return(null);
        }

        return(_displayNameCache.GetOrAdd(memberInfo, memberInfo => {
            if (!AttributeUtility.GetMemberNameFromNameAttributes(memberInfo, out string?name))
            {
                name = _defaultDisplayNameResolver(type, memberInfo, expression);
            }

            return name;
        }));
    }
    public static IRuleBuilderOptions <T, TProperty> WithNameFromDataAttribute <T, TProperty>(this IRuleBuilderOptions <T, TProperty> ruleBuilderOptions)
    {
        // Use reflection since contravariance only works with interface and delegates,
        // and we need it to handle generic collections.
        // Example: RuleBuilder<object, ICollection<object>> can't be cast to RuleBuilder<object, ICollection<object>>
        if (ruleBuilderOptions.GetType().GetGenericTypeDefinition() != typeof(RuleBuilder <,>))
        {
            throw new ValidationException($"Expected a RuleBuilder<{typeof(T).FullName}, {typeof(TProperty).FullName}>, got {ruleBuilderOptions.GetType().FullName}");
        }

        PropertyInfo ruleBuilderRulePropertyInfo = ruleBuilderOptions.GetType().GetProperty(nameof(RuleBuilder <T, TProperty> .Rule)) !;
        PropertyRule rule = (PropertyRule)ruleBuilderRulePropertyInfo.GetValue(ruleBuilderOptions) !;

        if (AttributeUtility.GetMemberNameFromNameAttributes(rule.Member, out string?dataName))
        {
            ruleBuilderOptions.OverridePropertyName(dataName);
        }

        return(ruleBuilderOptions);
    }