Shared configuration files in .NET

我们两清 提交于 2019-12-03 12:47:52

Well, you could "externalize" certain parts of the config's into separate .config files, and use them from both places.

E.g. you could externalize your connection string settings like so:

<connectionStrings configSource="connectionStrings.config" />

and then have the "connectionString.config" file like this:

<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
  <add name="ConfigurationDatabase" 
       connectionString="server=.;Integrated Security=true;database=test"/>
  <add name="TestDatabase" 
       connectionString="server=TEST;Integrated Security=true;database=test"/>
</connectionStrings>

Basically, any ConfigurationSection has such a "configSource" setting, which allows you to specify an external file to use.

That way, you might be able to share common parts of the two config files.

Marc

Zhaph - Ben Duguid

You will still need a web.config as there are elements of the configuration that are web specific that won't be in the app.config of your service. As Marc says, using the ConfigSource attribute will enable you to share common elements.

Note that the appSettings element has a slight difference: the File attribute.

Specifies a relative path to an external file that contains custom application configuration settings. The specified file contains the same kind of settings that are specified in the appSettings add, clear, and remove attributes and uses the same key/value pair format as those elements.

This behaves differently to the ConfigSource attribute, because you don't have to replace the entire section with the external file, it can just contain elements that you want to have in addition, or to override the values:

You can use the file attribute to specify a configuration file that provides additional settings or overrides the settings that are specified in the appSettings element.

If you are using ConfigSource to share other elements, then you will still have automatic restarts of the application when values are changed - the note about the restartOnExternalChanges attribute should be ignored for ASP.NET applications, however using the File attribute will mean that changes won't cause a restart.

The contents of the external files should still be cached, so perfromance shouldn't be impacted.

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