c# - Is it possible to bind configuration to stateless/readonly model in .Net Core -


so have model

public class connectionstrings {     public string sql { get; set; }     public string nosql { get; set; } } 

then have in appsettings.json follow:

"connectionstrings": {     "sql": "some connection string",     "nosql": "some other connection string" } 

then bind model follows:

services.configure<connectionstrings>(             options => configuration.getsection("connectionstrings").bind(options)); 

all works perfect doesn't make sense model mutable since holding important information , after configurations static information once read model should stay is. there other way of doing more safe?

code uses underhood configurationbinder expects public properties. bindproperty method:

// don't support set only, non public, or indexer properties if (property.getmethod == null ||    !property.getmethod.ispublic ||    property.getmethod.getparameters().length > 0) {    return; } 

as workaround, may suggest populating class manually. take following 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 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)); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -