Last active
January 24, 2023 14:25
-
-
Save cscott530/6be1ed952bfd225d3a0d8e5ebad023c1 to your computer and use it in GitHub Desktop.
Config Checker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Reflection; | |
namespace ConfigChecker; | |
public class Validator | |
{ | |
private NullabilityInfoContext _nullabilityContext = new NullabilityInfoContext(); | |
public void ValidateConfig<T>(T config) | |
{ | |
var props = config!.GetType().GetProperties(); | |
var invalid = props.Where(p => IsInvalid(config, p)); | |
if (invalid.Any()) | |
{ | |
throw new ArgumentException($"The following required properties had null values: [{string.Join(',', invalid.Select(i => i.Name))}]"); | |
} | |
} | |
private bool IsInvalid(object config, PropertyInfo property) | |
{ | |
var value = property.GetValue(config); | |
if (value != null) { | |
return false; | |
} | |
if (property.PropertyType.IsValueType) | |
{ | |
return Nullable.GetUnderlyingType(property.PropertyType) == null; | |
} | |
var nullabilityInfo = _nullabilityContext.Create(property); | |
if (nullabilityInfo.WriteState is not NullabilityState.Nullable) | |
{ | |
return true; | |
} | |
return false; | |
} | |
} | |
public class SampleConfig { | |
public string AwsKey { get; set; } = default!; | |
public string? NServiceBusConfig { get; set; } | |
} | |
public class Tester { | |
public static void Main(string[] args) { | |
var validator = new Validator(); | |
// Should work, all props set | |
validator.ValidateConfig(new SampleConfig | |
{ | |
AwsKey = "asdf", | |
NServiceBusConfig = "asdfasdf" | |
}); | |
// Missing NServiseBusConfig, but that's optional | |
validator.ValidateConfig(new SampleConfig | |
{ | |
AwsKey = "asdf" | |
}); | |
// Missing required prop, throws "System.ArgumentException: The following required properties had null values: [AwsKey]" | |
validator.ValidateConfig(new SampleConfig()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Throws an
ArgumentException
enumerating all non-nullable fields that are set to null after config has been hydrated.Could be extended to use the built-in data annotations as well (e.g.
[MinLength(1)]
to cause an empty string to be considered invalid, as well.