简体   繁体   English

C#:管理多个App.config文件

[英]C#: manage Multiple App.config files

I am facing a problem. 我正面临一个问题。

I have a dll which is interacting with a webservice and it saves its endpoint configuration in its app.config file. 我有一个与web服务交互的DLL,它将端点配置保存在app.config文件中。

I want to use this dll from my host application. 我想在我的宿主应用程序中使用这个dll。 The host application has its own config file. 主机应用程序有自己的配置文件。 I have to merge the contents of dll's config to host's config each time when I change service endpoint. 每次更改服务端点时,我都必须将dll配置的内容合并到主机的配置中。

Is there a way that I can use both config files. 有没有办法可以使用两个配置文件。 So the dll uses its own config whereas host application use its own config. 所以dll使用自己的配置,而主机应用程序使用自己的配置。

config files can include external files. 配置文件可以包含外部文件。

If you'd put the endpoint's config onto an external file, and then include it in yout host, you won't need to change the host's config every time 如果您将端点的配置放在外部文件上,然后将其包含在您的主机中,则无需每次都更改主机的配置

eg: in your app.config file: 例如:在你的app.config文件中:

...
<configSections>
  ...
  <section name="myEndpoint" type="System.Configuration.DictionarySectionHandler" />
  ...
</configSections>
...
<myEndpoint configSource="myEndpoint.config" />

then myEndpoint.config could look like that: 然后myEndpoint.config看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<myEndpoint>
  <add key="myKey" value="myValue" />
</myEndpoint>

and you can access the values from your code, similarly to reading normal app settings, like that: 并且您可以访问代码中的值,类似于阅读正常的应用设置,如下所示:

var myEndpointConfig = (Hashtable)ConfigurationManager.GetSection("myEndpoint");
Console.WriteLine(myEndpointConfig["myKey"]);

The right way is to merge the DLL's config file into the EXE's; 正确的方法是将DLL的配置文件合并到EXE中; that'll work out of the box. 这将开箱即用。 But see .NET DLL Settings and Config when there's a Web Reference - whats going on? 但是,当有Web引用时,请参阅.NET DLL设置和配置 - 最新情况如何? for a way to explicitly open a config file and read it. 用于显式打开配置文件并读取它的方法。 The problem is that you'd need to FIND the config file first, and that's not necessarily easy. 问题是你需要先找到配置文件,这不一定容易。 If the DLL is just sitting around, you could check the same directory. 如果DLL只是坐在那里,你可以检查同一目录。 But if it's in the GAC, where do you look? 但如果它在GAC中,你在哪里看? I suggest sticking to the right way. 我建议坚持正确的方式。

如果您使用svcutil生成代理,这可能有所帮助:检查/config:/mergeConfig开关,您可以指定哪些配置文件接收生成的信息,您可以将其合并而不是仅覆盖已存在的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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