简体   繁体   中英

Sharing connectionstrings between 2 .NET applications

Suppose I have an ASP.NET website running with its corresponding web.config file, which contains a bunch of connectionstrings for database access. I also have a little helper console program (deployed to the same folder as the web app) that does maintenance tasks and other stuff. This helper programs shares a bunch of dll's with the web app, so i have to keep a separate bla.exe.config file for it so the shared dll's find the connection strings and etc. I want to be able to make the console app use the web.config instead of having its own config file.

So far I've managed to load the appSettings at runtime (using ConfigurationManager.OpenMappedExeConfiguration , looping through the appsettingts and adding them dynamically to the ConfigurationManager.AppSettings collection), but the ConfigurationManager.ConnectionStrings member is apparently read-only so i cannot 'inject' the web.config's connectionstrings into it.

Any ideas?

Personally I would just program a way so that both applications can find the same file. I would use something like Environment.SpecialFolder using the CommonApplicationData enumeration. You might consider the machine.config file though it's generally not recommended.

You could try to use the configSource attribute of the connectionStrings section, to reference an external file. I haven't tried it, but something like this:

<connectionStrings configSource="..\connnectionstrings.config">

connectionstrings.config:

<connectionStrings>
  <add name="..." connectionString="Server=...;Database=..;" />
</connectionStrings>

Update:

The approach shown above does not work. The configSource element does not support absolute paths, or relative paths starting with "..\\".

I know this is a very old question but you could consider storing the connection strings in a shared class library's app.config and using the method in the below SO answer to ensure that config file is always copied to the referencing project's bin folder as shared.project.dll.config . Then you just read shared.project.dll.config from the referencing project's bin folder to get the connection string.

Visual Studio/MSBuild copy referenced class library's app.config as *.dll.config to bin folder of current project

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