You are correct: calling Configure<T>
sets up the options infrastructure for T
. This include IOptions<T>
, IOptionsMonitor<T>
and IOptionsSnapshot<T>
. In its simplest forms, configuring the value uses an Action<T>
or as in your example binding to a specific IConfiguration
. You may also stack multiple calls to either form of Configure
. This then allows you to accept an IOptions<T>
(or monitor/snapshot) in your class' constructor.
The easiest way to determine if binding to an IConfigurationSection
is working as you intend it to is to manually perform the binding and then inspect the value:
var opts = new MyClass();
var config = Configuration.GetSection("MyClass");
// bind manually
config.Bind(opts);
// now inspect opts
The above is dependant on the Microsoft.Extensions.Configuration.Binder
package which you should already have as a transitive dependency if you are referencing the Options infrastructure.
Back to your issue: the binder will only bind public
properties by default. In your case MyClass.MyList
is a field. To get the binding to work you must change it to a property instead.
If you wanted/needed to bind non-public
properties you could pass an Action<BinderOptions>
:
// manually
var opts = new MyClass();
var config = Configuration.GetSection("MyClass");
// bind manually
config.Bind(opts, o => o.BindNonPublicProperties = true);
// DI/services
var config = Configuration.GetSection("MyClass");
services.Configure<MyClass>(config, o => o.BindNonPublicProperties = true);
Even with BinderOptions
there is still no way to bind to fields. Also note that there is varying behavior for things like collection interfaces, arrays and get
only properties. You may need to play around a bit to ensure things are binding as you intend.
var o = new MyModel(); Configuration.GetSection("MyModel").Bind(o);
and then inspecto
which should now be populated. You might need a reference toMicrosoft.Extensions.Configuration.Binder
if you don't already have it via transitive references. – EinhornMyList
is a field. The binder only works with properties so add{ get; set; }
and you should be good to go – Einhorn