Is it possible to bind configuration to stateless/readonly model in .NET Core?
code like this uses underhood the ConfigurationBinder
that expects public properties. From BindProperty method:
// We don't support set only, non public, or indexer properties
if (property.GetMethod == null ||
!property.GetMethod.IsPublic ||
property.GetMethod.GetParameters().Length > 0)
{
return;
}
As a workaround, I may suggest populating your class manually. Take the following as an example:
public class ConnectionStrings
{
public ConnectionStrings(string sql, string noSql)
{
Sql = sql;
NoSql = noSql;
}
public string Sql { get; private set; }
public string NoSql { get; private set; }
}
and then in ConfigureServices
method:
var sqlValue = Configuration.GetValue<string>("ConnectionStrings:Sql", string.Empty);
var noSqlValue = Configuration.GetValue<string>("ConnectionStringsApp:NoSql", string.Empty);
services.Configure<ConnectionStrings>(
options => new ConnectionStrings(sqlValue, noSqlValue));
As an alternative, for version 2.1+, you can now bind to non-public properties by specifying to do so with BinderOptions
:
services.Configure<ConnectionStrings>(options =>
Configuration.GetSection("ConnectionStrings")
.Bind(options, c => c.BindNonPublicProperties = true));
or to just get them:
var connectionStrings = Configuration.GetSection("ConnectionStrings")
.Get<ConnectionStrings>(c => c.BindNonPublicProperties = true);