You can also convert your appSetting section to a variable that you can inject in any constructors.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="MyValue1" value="MyString"
<add key="MyValue2" value="600"
<add key="MyValue3" value="https://stackoverflow.com/"
</appSettings>
</configuration>
Declare an class as bellow:
public class AppSettings
{
public string MyValue1 { get; set; }
public int MyValue2 { get; set; }
public Uri MyValue3 { get; set;}
}
Declare the extension function ToVariable() in a new static class as bellow:
public static class ObjectExtension
{
public static T ToVariable<T>(this object data) where T : class, new()
{
if (data is NameValueCollection dataCollection)
{
var target = new T();
var targetProperties = target.GetType()?.GetProperties() ;
foreach(string key in dataCollection.AllKeys)
{
var property = targetProperties.FirstOrDefault(x => x.Name.Equals(key, System.StringComparison.InvariantCultureIgnoreCase));
if (property != null)
{
switch (Type.GetTypeCode(property.PropertyType))
{
case TypeCode.String:
property.SetValue(target, dataCollection[key], null);
break;
case TypeCode.Int32:
property.SetValue(target, Int32.Parse(dataCollection[key].ToString()), null);
break;
case TypeCode.Object:
switch (property.PropertyType.Name)
{
case nameof(Uri):
property.SetValue(target, new Uri(dataCollection[key].ToString()), null);
break;
default: throw new NotImplementedException($"The Object type [{property.PropertyType.Name}] is not implemented for the property [{property.Name}]");
}
break;
default:
throw new NotImplementedException($"The Type [{property.PropertyType}] is not implemented for the property [{property.Name}]");
}
}
}
return target;
}
return default(T);
}
}
And finally you can use it in your Global.asax or OWIN Startup class as bellow:
var appSettings = ConfigurationManager.GetSection("appSettings").ToVariable<AppSettings>();