In the following console application (.Net core 2.0), the conn
got a null value.
var services = new ServiceCollection();
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddXmlFile("App.config", optional: false).Build();
services.AddSingleton(configuration);
var conn = configuration.GetConnectionString("MyConn"); // conn is null
The following is App.config.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConn" connectionString="....." />
</connectionStrings>
<Settings>
<Name>Test</Name>
</Settings>
</configuration>
There is some code which can get the value ("Test") of Name
of the Settings
successfully.
Update:
Right after the assignment of conn
, I have the following code to get <Settings>
section of the XML part and it can get the value "Test".
var myOptions = new MyOptions();
configuration.GetSection("Settings").Bind(myOptions);
.NET Core's Configuration does not treat .config files any different than XML files. That is, you can't add the connection string "the old way", by having an
add
tag, as this would create quite weird config keys:If you want to use XML files, the correct way of specifying the connection string would be:
See,
GetConnectionString
is just an extension method that simply do the following:If during debugging you check
Data
inconfiguration.Providers
for you will find the following keys/values among others:That's actually why you got a
null
value.So with the current XML structure, you can simply do:
Or modify your XML to
and use