/// <summary> /// Fill this configuration from <see cref="EnvironmentAttribute">env</see>. /// </summary> public void FillFromEnv() { PropertyInfo[] props = this.GetType().GetProperties(); foreach (PropertyInfo prop in props) { EnvironmentAttribute attr = prop.GetCustomAttribute <EnvironmentAttribute>(); if (attr != null) { string env = Environment.GetEnvironmentVariable(attr.Name); if (env != null) { if (prop.PropertyType != typeof(string)) { try { prop.SetValue(this, Activator.CreateInstance(prop.PropertyType, env)); } catch (TargetInvocationException e) { throw new ConfigException(prop.Name, attr.Name, e.InnerException); } catch (Exception e) { throw new ConfigException(prop.Name, attr.Name, "Type Problem. See InnerException for Details.", e); } } else { prop.SetValue(this, env); } } } } }
/// <summary> /// Perform validation via <see cref="IsValid(out List{ValidationResult})"/> and throw an <see cref="ConfigException"/> if it is not valid. /// </summary> public void Validate() { if (!this.IsValid(out List <ValidationResult> results)) { foreach (ValidationResult result in results) { string propName = result.MemberNames.First(); Type t = this.GetType(); EnvironmentAttribute attr = t.GetProperty(propName).GetCustomAttribute <EnvironmentAttribute>(); if (attr != null) { log.Error("ENV: {env} -> {message}", attr.Name, result.ErrorMessage); } } throw new ConfigException("Please check your enviroment variables, config is not valid!"); } }