This repository was archived by the owner on Dec 18, 2018. It is now read-only.
This repository was archived by the owner on Dec 18, 2018. It is now read-only.
ConfigurationExtensions.Get<T>() should support TypeConverters #130
Closed
Description
The current implementation uses Convert.ChangeType
which only handles types that implement IConvertible
.
A small change to allow the use of TypeConverters would improve mapping values to other types.
e.g.
#if NET45 || ASPNET50 || ASPNETCORE50
public static T Get<T>(this IConfiguration configuration, string key)
{
var type = typeof(T);
var value = configuration.Get(key);
#if ASPNETCORE50
return (T)Convert.ChangeType(value, type);
#elif NET45 || ASPNET50
if (typeof(IConvertible).IsAssignableFrom(type))
{
return (T)Convert.ChangeType(value, type);
}
else
{
var converter = TypeDescriptor.GetConverter(type);
if (converter == null) throw new InvalidCastException("Could not find a valid TypeConverter for type " + type.FullName);
return (T)converter.ConvertFromInvariantString(value);
}
#endif
}
#endif