Skip to content

Commit 0e98844

Browse files
committed
Added conversion of properties to UpperCaseSnakeCase
Added conversion to UpperCaseSnakeCase in case the names of AppSettings class properties do not match the keys in the .env file.
1 parent 6c4040f commit 0e98844

2 files changed

Lines changed: 26 additions & 6 deletions

File tree

src/Binder/EnvBinder.cs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Text;
12
using System;
23
using System.Collections.Generic;
34
using System.Reflection;
@@ -42,19 +43,22 @@ public EnvBinder(IEnvironmentVariablesProvider provider)
4243
/// <inheritdoc />
4344
public TSettings Bind<TSettings>(out EnvValidationResult result) where TSettings : new()
4445
{
45-
var settings = new TSettings();
46-
var type = typeof(TSettings);
47-
result = _validationResult;
46+
var sb = new StringBuilder(capacity: 40);
47+
var envVars = _configuration.EnvVars;
48+
var settings = new TSettings();
49+
var type = typeof(TSettings);
4850
var properties = _configuration.BindNonPublicProperties ? type.GetPublicAndNonPublicProperties() : type.GetProperties();
51+
result = _validationResult;
4952
foreach (PropertyInfo property in properties)
5053
{
5154
if(IsReadOnlyOrWriteOnly(property))
5255
continue;
5356

5457
var envKeyAttribute = (EnvKeyAttribute)Attribute.GetCustomAttribute(property, typeof(EnvKeyAttribute));
55-
var variableName = envKeyAttribute is not null ? envKeyAttribute.Name : property.Name;
56-
var retrievedValue = _configuration.EnvVars[variableName];
57-
58+
var variableName = envKeyAttribute is not null ? envKeyAttribute.Name : property.Name;
59+
var retrievedValue = envVars[variableName];
60+
retrievedValue ??= envKeyAttribute is not null ? retrievedValue : envVars[variableName.ToUpperCaseSnakeCase(sb)];
61+
sb.Clear();
5862
if (retrievedValue is null)
5963
{
6064
string errorMsg;

src/Extensions/StringExtensions.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,21 @@ public static bool EndsWith(this string str, char value)
3636
int len = str.Length;
3737
return len != 0 && str[len - 1] == value;
3838
}
39+
40+
/// <summary>
41+
/// Converts from PascalCase to UpperCaseSnakeCase.
42+
/// </summary>
43+
/// <param name="str"></param>
44+
/// <param name="sb"></param>
45+
/// <returns></returns>
46+
public static string ToUpperCaseSnakeCase(this string str, StringBuilder sb)
47+
{
48+
int len = str.Length;
49+
sb.Append(str[0]);
50+
for (int i = 1; i < len; i++)
51+
sb.Append(char.IsUpper(str[i]) ? $"_{str[i]}" : char.ToUpper(str[i]));
52+
53+
return sb.ToString();
54+
}
3955
}
4056
}

0 commit comments

Comments
 (0)