Using connection strings twice in the web.config file; another for nlog configuration

I am using nlog in my project. My web.config looks like this:

<connectionStrings>
  <add name="SQL_ConnStr" connectionString="Initial Catalog=ConfigDB;Provider=SQLOLEDB; Data Source=mysqlserver; User ID=sa; Password=sa; Persist Security Info=True;"/>
</connectionStrings>
...
<nlog>
<targets>
  <target name="database" type="Database" dbProvider="sqlserver" **connectstring="Initial Catalog=ConfigDB;Provider=SQLOLEDB; Data Source=mysqlserver; User ID=sa; Password=sa"** commandText="INSERT INTO ...">
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="database"/>
</rules>
</nlog>

Two identical connection strings! My question is how to save only one connection string?

+5
source share
2 answers

First add the add providerName attribute to the connection string. Then use connectionStringName instead of connectionString and refer to the connection string from the settings.

<connectionStrings>
  <add name="SQL_ConnStr" 
       providerName="System.Data.SqlClient"
       connectionString="Initial Catalog=ConfigDB;Provider=SQLOLEDB; Data Source=mysqlserver; User ID=sa; Password=sa; Persist Security Info=True;"/>
</connectionStrings>
...
<nlog>
  <targets>
    <target name="database" 
            type="Database" 
            dbProvider="sqlserver"
            connectionStringName="SQL_ConnStr" 
            commandText="INSERT INTO ...">
    </target>
  </targets>
  <rules>
    <logger name="*" 
            minlevel="Debug" 
            writeTo="database"/>
  </rules>
</nlog>
+16
source

This should be possible using the ConnectionStringName property of the target element.

For ex:

<targets>
  <target name="database" type="Database" connectionStringName="SQL_ConnStr" commandText="INSERT INTO ...">
</target>

This will result in direct access to the connection string from the connection string section.

+6

All Articles