Is it possible to bind configuration to stateless/readonly model in .NET Core?

Viewed 4734

Normally, we would have some model

public class ConnectionStrings
{
    public string Sql { get; set; }
    public string NoSql { get; set; }
}

then we have something in appsettings.json as follow:

"ConnectionStrings": {
    "Sql": "some connection string",
    "NoSql": "some other connection string"
}

Then I bind the model as follows:

services.Configure<ConnectionStrings>(
            options => Configuration.GetSection("ConnectionStrings").Bind(options));

All works perfectly, but it doesn't make sense for my model to be mutable since it is holding important information. After all, configurations are static information, so once my model is read, it should stay like it is.

Is there any other way of doing this more safely?

3 Answers

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);
Related