Centralize connection strings for multiple projects within the same solution

。_饼干妹妹 提交于 2019-11-28 21:34:26

There's a few ways you could do it:

  1. Put common configuration settings in machine.config as shown here
  2. Put common configuration settings in a central file and link to that in each projects's app.config as shown here
  3. Store the configuration settings in the registry

For me, i always work with the last solution :) Good luck!

You can share the connection strings among multiple projects in a solution as follows:

  1. Create a ConnectionStrings.config file with your connection strings under a solution folder, this file should contain only the section connectionStrings

  2. In your projects, add this config file As a Link (add existing item, add as link)

  3. Select the added file and set its property Copy to Output Directory to Copy always or Copy if newer
  4. In the App.config of your projects, point to the linked ConnectionStrings.config file using the configSource attribute: <connectionStrings configSource="ConnectionStrings.config" />

ConnectionStrings.config

<connectionStrings>
    <add name="myConnStr" connectionString="Data Source=(local); Initial Catalog=MyDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    ...
    <connectionStrings configSource="ConnectionStrings.config" />
    ...
</configuration>

Read more details....

Martin Mulder

First, take a look at this post. It describes how you can share the same app.config between multiple projects.

How to Share App.config?

Second, take a look at one other post, which describes how you let different app.config-files have a reference to one single shared xml-file which contains the connection strings.

Use XML includes or config references in app.config to include other config files' settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!