Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

configuration.GetConnectionString("MyConn") got null value?

Tags:

c#

.net-core

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);
like image 955
ca9163d9 Avatar asked Aug 29 '17 20:08

ca9163d9


2 Answers

See, GetConnectionString is just an extension method that simply do the following:

public static string GetConnectionString(this IConfiguration configuration, string name)
{
    return configuration?.GetSection("ConnectionStrings")?[name];
}

If during debugging you check Data in configuration.Providers for you will find the following keys/values among others:

key: "connectionStrings:add:MyConn:name" | value: "MyConn"
key: "connectionStrings:add:MyConn:connectionString" | value: "....."

That's actually why you got a null value.


So with the current XML structure, you can simply do:

var connString = configuration.GetValue<string>("connectionStrings:add:MyConn:connectionString", string.Empty);

Or modify your XML to

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <MyConn>conn_string_here</MyConn>
  </connectionStrings>
</configuration>

and use

var conn = configuration.GetConnectionString("MyConn");
// conn value will be "conn_string_here"
like image 149
Set Avatar answered Oct 19 '22 22:10

Set


.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:

Configuration provider internals

If you want to use XML files, the correct way of specifying the connection string would be:

<connectionStrings>
  <MyConn>....</MyConn>
</connectionStrings>
like image 24
Michał Dudak Avatar answered Oct 19 '22 23:10

Michał Dudak