Example #1
0
        /// <summary>
        /// Returns the expected configuration key with full path, for the given option.
        /// </summary>
        public static string GetKey <TOptions, TProperty>(Expression <Func <TOptions, TProperty> > propertySelector)
        {
            string path        = OptionsAttribute.GetConfigurationPath <TOptions>();
            string propertyKey = ((MemberExpression)propertySelector.Body).Member.Name;

            if (string.IsNullOrEmpty(path))
            {
                return(propertyKey);
            }
            else
            {
                return(path + ConfigurationPathSeparator + propertyKey);
            }
        }
Example #2
0
        public T GetOptions <T>(string configurationPath = "", bool requireAllMembers = false) where T : class
        {
            var optionsType     = typeof(T);
            var optionsInstance = Activator.CreateInstance(optionsType);

            if (string.IsNullOrEmpty(configurationPath))
            {
                configurationPath = OptionsAttribute.GetConfigurationPath <T>();
            }

            var props   = optionsType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(prop => prop.CanWrite);
            var fields  = optionsType.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(field => !field.IsInitOnly);
            var members = props.Cast <MemberInfo>().Concat(fields.Cast <MemberInfo>()).ToList();

            var membersBound = new List <MemberInfo>();

            foreach (var member in members)
            {
                bool convertRelativePath = member.GetCustomAttribute <AbsolutePathOptionAttribute>() != null;
                if (TryGetConfigurationValueForMemberName(member.Name, out var memberValue, configurationPath, convertRelativePath))
                {
                    SetMemberValue(optionsInstance, member, memberValue);

                    if (requireAllMembers)
                    {
                        membersBound.Add(member);
                    }
                }
            }

            if (requireAllMembers && membersBound.Count != members.Count)
            {
                var missing = members.Where(member => !membersBound.Contains(member)).Select(member => member.Name);
                throw new FrameworkException($"Binding requires all members to be present in configuration, but some are missing: {string.Join(",", missing)}.");
            }

            return((T)optionsInstance);
        }