Add Bind<T> overload that creates T

This commit is contained in:
Hao Kung 2016-09-30 14:17:39 -07:00
Родитель 38f770870c
Коммит f1b65399d9
2 изменённых файлов: 24 добавлений и 11 удалений

Просмотреть файл

@ -33,6 +33,25 @@ namespace Microsoft.Extensions.Configuration
}
}
/// <summary>
/// Attempts to bind a new instance of T to configuration values by matching property names against configuration keys recursively.
/// </summary>
/// <typeparam name="T">The type of the new instance to bind.</typeparam>
/// <param name="configuration">The configuration instance to bind.</param>
/// <returns>The new instance of T</returns>
public static T Bind<T>(this IConfiguration configuration) where T : new()
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
var instance = new T();
BindInstance(instance.GetType(), instance, configuration);
return instance;
}
/// <summary>
/// Extracts the value with the specified key and converts it to type T.
/// </summary>

Просмотреть файл

@ -97,11 +97,9 @@ namespace Microsoft.Extensions.Configuration.Binder.Test
configurationBuilder.AddInMemoryCollection(dic);
var config = configurationBuilder.Build();
var options = new ConfigurationInterfaceOptions();
config.Bind(options);
var options = config.Bind<ConfigurationInterfaceOptions>();
var childOptions = new DerivedOptions();
options.Section.Bind(childOptions);
var childOptions = options.Section.Bind<DerivedOptions>();
Assert.True(childOptions.Boolean);
Assert.Equal(-2, childOptions.Integer);
@ -129,15 +127,11 @@ namespace Microsoft.Extensions.Configuration.Binder.Test
configurationBuilder.AddInMemoryCollection(dic);
var config = configurationBuilder.Build();
var options = new ConfigurationInterfaceOptions();
config.Bind(options);
var options = config.Bind<ConfigurationInterfaceOptions>();
var childOptions = new DerivedOptionsWithIConfigurationSection();
options.Section.Bind(childOptions);
var childOptions = options.Section.Bind<DerivedOptionsWithIConfigurationSection>();
var childDerivedOptions = new DerivedOptions();
childOptions.DerivedSection.Bind(childDerivedOptions);
var childDerivedOptions = childOptions.DerivedSection.Bind<DerivedOptions>();
Assert.True(childOptions.Boolean);
Assert.Equal(-2, childOptions.Integer);