Skip to content

Instantly share code, notes, and snippets.

@cscott530
Last active January 24, 2023 14:25
Show Gist options
  • Save cscott530/6be1ed952bfd225d3a0d8e5ebad023c1 to your computer and use it in GitHub Desktop.
Save cscott530/6be1ed952bfd225d3a0d8e5ebad023c1 to your computer and use it in GitHub Desktop.
Config Checker
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());
}
}
@cscott530
Copy link
Author

cscott530 commented Jan 24, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment