From f1b65399d9508d490dcb0d5f006c69213182262c Mon Sep 17 00:00:00 2001 From: Hao Kung Date: Fri, 30 Sep 2016 14:17:39 -0700 Subject: [PATCH] Add Bind overload that creates T --- .../ConfigurationBinder.cs | 19 +++++++++++++++++++ .../ConfigurationBinderTests.cs | 16 +++++----------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.Extensions.Configuration.Binder/ConfigurationBinder.cs b/src/Microsoft.Extensions.Configuration.Binder/ConfigurationBinder.cs index 5e74660..668cfa5 100644 --- a/src/Microsoft.Extensions.Configuration.Binder/ConfigurationBinder.cs +++ b/src/Microsoft.Extensions.Configuration.Binder/ConfigurationBinder.cs @@ -33,6 +33,25 @@ namespace Microsoft.Extensions.Configuration } } + /// + /// Attempts to bind a new instance of T to configuration values by matching property names against configuration keys recursively. + /// + /// The type of the new instance to bind. + /// The configuration instance to bind. + /// The new instance of T + public static T Bind(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; + } + + /// /// Extracts the value with the specified key and converts it to type T. /// diff --git a/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs b/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs index ebd2864..827a98b 100644 --- a/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs +++ b/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs @@ -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(); - var childOptions = new DerivedOptions(); - options.Section.Bind(childOptions); + var childOptions = options.Section.Bind(); 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(); - var childOptions = new DerivedOptionsWithIConfigurationSection(); - options.Section.Bind(childOptions); + var childOptions = options.Section.Bind(); - - var childDerivedOptions = new DerivedOptions(); - childOptions.DerivedSection.Bind(childDerivedOptions); + var childDerivedOptions = childOptions.DerivedSection.Bind(); Assert.True(childOptions.Boolean); Assert.Equal(-2, childOptions.Integer);