Reputation: 1569
In my Asp.net Core 2.0 application, I am trying to implement the design of not to use the IConfiguration constructor dependency for connection strings in my class library project as advised by @Nkosi here.
In this approach it is unable to bind the configuration instance to the new instance of type as in the following lines of code
public void ConfigureServices(IServiceCollection services) {
//...
var settings = Configuration
.GetSection("ConnectionStrings:OdeToFood")
.Get<ConnectionSetings>();
//...verify settings (if needed)
services.AddSingleton(settings);
}
public class ConnectionSetings
{
public string Name { get; set; }
}
I can see Configuration.GetSection("ConnectionStrings:OdeToFood")
returning the "Key", "Path" and "Value" attributes but it fails to do the bindings and return null in settings.
I have seen similar questions where ppl have recommended solutions like as follow but none of them is working for me.
services.Configure<ConnectionsSetings>(Configuration.GetSection("ConnectionStrings:OdeToFood"));
Also,
Configuration
.GetSection("ConnectionStrings:OdeToFood").Bind<>
Following is the appsettings.json
{
"Greeting": "Hello!!!",
"ConnectionStrings": {
"OdeToFood": "Server=(localdb)\\MSSQLLocalDB;Database=OdeToFood;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Following is the immediate window screen shot of Configuration.GetSection output where I can see Key, Path and Value
From the following screenshot it can be seen the setting variable is coming null
Upvotes: 1
Views: 1744
Reputation: 9175
I'm not sure what you want to achieve with provided code, but in order to get value instead of null, you should have the following section in your appsettings.json:
{
...
"ConnectionStrings": {
"OdeToFood": {
"Name": "someConncetionString"
}
},
...
}
Then the following code will return the object:
var settings = Configuration
.GetSection("ConnectionStrings:OdeToFood")
.Get<ConnectionSetings>();
Upvotes: 2