简体   繁体   中英

Is it possible to create a solution level configuration file in Visual Studio?

I have a solution with multiple projects that will use the same connection strings. I can add a configuration file to each project with these strings, but was wondering if there was a way to add a single configuration file for the entire solution that could be accessed by all the individual projects within it?

Instead of adding the config file to each project, use Add as Link so that there is only one copy of the file that all the projects are accessing.

Essentially you're adding the address rather than the file itself which means that any changes to the file at the address will affect all projects reading from the address.

Create config once in your first project.

Then all other projects, add the existing item, but hit the arrow on the Add button and Add As Link instead.

The one file will be shared amongst your projects.

I belive you only need the config file in the 'Startup' project.

I have a solution with multiple projects in that all use the same connection string from a single config file in the startup project.

alternatively, you could create your own config file which all projects access (not using the .net config file)

Depending on the projects you have in the solution if you have a MVC/UI project you can use the web.config from that and reference it in other projects within the same solution.

Sample:

Web.config in MVC project:

<configuration>
...
  <connectionStrings>
    <add name="name1" connectionString="Data Source=HOSTNAME_DB_INSTANCE;Initial Catalog=DB_NAME;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="name2" connectionString="Data Source=HOSTNAME_DB_INSTANCE;Initial Catalog=DB_NAME;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="name3" connectionString="Data Source=HOSTNAME_DB_INSTANCE;Initial Catalog=DB_NAME;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
...
</configuration>

In another project/class library

public List<Products> GetProducts()
{
    using (var multi = new SqlConnection(ConfigurationManager.ConnectionStrings["name1"].ConnectionString).QueryMultiple("SPROC NAME", commandType: CommandType.StoredProcedure))
    {
        return multi.Read<Products>().ToList();
    }    
}

This has always worked for me at a solution level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM