2

I am using .net core 3.1 to read connection string using IOption but the value is coming out to be null(settings.Value.ConnectionString in the below code). Can someone help please? In the ConfigureServices of Startup, the config section is coming out fine. But not in the controller it is coming out as null.

public class DatabaseSettings
{
  public string ConnectionString {get; set;}
}

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

public class DefaultController : ControllerBase
{
  private string _connectionString;
  public DefaultController(IOptions<DatabaseSettings> settings)
  {
    _connectionString = settings.Value.ConnectionString;
  }  
}

1 Answer 1

3

Change the approach and extract the connection string from configuration and modify the options..

services.Configure<DatabaseSettings>(options => {
    string connectionString = Configurations.GetConnectionsString("ABCDB");
    options.ConnectionString = connectionString;
});

The original approach was not following binding by convention so the desired properties were not being populated.

If following a conventional approach then the model class would need to be refactored

Lets change the name for demonstration purposes.

public class ConnectionStrings {
    public string ABCDB { get; set; }
}

Using conventional approach can be done in multiple ways, as already demonstrated above, but here is another example

services.Configure<ConnectionStrings>(Configurations.GetConnectionsStrings());

This would be used then like

public class DefaultController : ControllerBase {
    private string _connectionString;
    public DefaultController(IOptions<ConnectionStrings> settings) {
        _connectionString = settings.Value.ABCDB;
    }  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.