如何让 .NET 类库读取自己的配置文件?

发布于 2024-10-24 03:17:36 字数 390 浏览 3 评论 0原文

我有一个 .NET 类库,它提供了一组供多个 Web 服务使用的辅助函数。该类库必须存储单个设置,特别是一个连接字符串,Web 服务本身不需要看到该设置,因为它们都必须查询相同的数据库。

不幸的是,.NET 没有提供轻松读取 DLL 的 app.config 文件的方法。唯一“简单”的解决方案是将连接字符串存储在每个 Web 服务配置文件中,这完全是胡说八道。

通常,我关心代码的优雅性,但这次我真的需要一个解决方案,即使它是一个 hack。有没有办法让.NET类库有自己的配置?


编辑:从技术上讲,我可以将所有这些 Web 服务合并到一个 Web 服务中。但是,出于商业原因(每个 Web 服务将单独出售),我不能这样做。

I have a .NET class library that provides a set of helper functions that are used by several Web Services. This class library must store a single setting, specifically, a connection string, which need not be seen by the Web Services themselves, since they all must query the same datbase.

Unfortunately, .NET provides no means to easily read a DLL's app.config file. The only "easy" solution would be to store the connection string in every single Web Service configuration file, which is completely bollocks.

Normally, I care about code elegance, but this time I really need a solution, even if it is a hack. Is there any way to make a .NET class library have its own configuration?


EDIT: Technically, I could merge all those Web Services into a single Web Service. But, for business reasons (each Web Service will be sold separately), I cannot do that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

将军与妓 2024-10-31 03:17:36

我知道已经过时一年了,但我使用这种方法来读取每个设置:

Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
ConfigurationSectionGroup csg = config.GetSectionGroup("applicationSettings");
ClientSettingsSection c = (ClientSettingsSection)csg.Sections["Add your section name here, e.g. Your.Namespace.Properties.Settings"];
foreach (SettingElement e in c.Settings)
{
    Debug.WriteLine("SETTING NAME: " + e.Name);
    SettingValueElement v = e.Value;
    Debug.WriteLine("SETTING VALUE: " + v.ValueXml.InnerText);
}

这适用于在类库项目中创建的设置文件。设置文件应命名为“YourLibrary.dll.config”,然后部署在库的位置。设置文件应具有与此类似的内容:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Your.NameSpace.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <Your.NameSpace.Properties.Settings>
      <setting name="YourLibrary_WebReferences_YourWebService" serializeAs="String">
        <value>http://localhost:3861/YourWebService.asmx</value>
      </setting>
      <setting name="AnotherSetting" serializeAs="String">
        <value>False</value>
      </setting>
    </Your.NameSpace.Properties.Settings>
  </applicationSettings>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

我不需要从配置文件中读取连接字符串,但这应该可以通过更改打开 exe 配置后获得的节组的名称来实现。

我需要这样做的原因是我有一个用户控件,它包装了一个 ActiveX/COM 库,然后将其托管在 IE 中的“对象”标记中。我已经使用了“param”标签,因此我可以使用该机制将设置传递到用户控件中,但这种方法当时似乎是一个合乎逻辑的选择。另外,我不会让这个特殊的问题打败我!

HTH 普里德莫尔 :)

A year out of date I know, but I used this method to read each of the settings:

Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
ConfigurationSectionGroup csg = config.GetSectionGroup("applicationSettings");
ClientSettingsSection c = (ClientSettingsSection)csg.Sections["Add your section name here, e.g. Your.Namespace.Properties.Settings"];
foreach (SettingElement e in c.Settings)
{
    Debug.WriteLine("SETTING NAME: " + e.Name);
    SettingValueElement v = e.Value;
    Debug.WriteLine("SETTING VALUE: " + v.ValueXml.InnerText);
}

This works on a settings file created in a Class Library Project. The settings file should be named "YourLibrary.dll.config" and then deployed in the library's location. The settings file should have similar content to this:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Your.NameSpace.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <Your.NameSpace.Properties.Settings>
      <setting name="YourLibrary_WebReferences_YourWebService" serializeAs="String">
        <value>http://localhost:3861/YourWebService.asmx</value>
      </setting>
      <setting name="AnotherSetting" serializeAs="String">
        <value>False</value>
      </setting>
    </Your.NameSpace.Properties.Settings>
  </applicationSettings>
  <startup>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

I haven't needed to read connection strings from the config file, but that should be possible by changing the name of the section group that you get after opening the exe configuration.

The reason why I needed to do this is that I have a User Control which wraps a ActiveX/COM library which is then hosted in IE in an "object" tag. I have got the use of "param" tags working, so I could have used that mechanism to have passed the settings into the User Control, but this method seemed a logical choice at the time. Plus I wasn't going to let this particular problem beat me!

HTH pridmorej :)

甲如呢乙后呢 2024-10-31 03:17:36

我认为您正在寻找:

ConfigurationManager.OpenExeConfiguration(string exePath)

ConfigurationManager.OpenMappedExeConfiguration(
    new ExeConfigurationFileMap() { 
        ExeConfigFilename = path + "app.config" 
    }, ConfigurationUserLevel.None);

返回 配置对象。 ConfigurationManager 上的 MSDN 文档

尝试 这个问题了解如何获取DLL路径。

I think you're looking for:

ConfigurationManager.OpenExeConfiguration(string exePath)

or

ConfigurationManager.OpenMappedExeConfiguration(
    new ExeConfigurationFileMap() { 
        ExeConfigFilename = path + "app.config" 
    }, ConfigurationUserLevel.None);

Which returns a Configuration object. MSDN doc on ConfigurationManager

Try this question for how to get the DLL path.

筱果果 2024-10-31 03:17:36

使用企业库共享配置源”和“差异配置”(用于在多个环境之间轻松切换)可以很好地解决这种配置问题, ETC。)。

要了解高级配置方案,请尝试从此处开始:

http://msdn.microsoft.com/en-us/library/ff664552(v=pandp.50).aspx

并集成企业库配置工具Visual Studio 中使用 Visual Studio 中的 (GUI),请在此处尝试:

http://visualstudiogallery.msdn.microsoft.com/029292f0-6e66-424f-8381-3454c8222f9a

学习曲线乍一看可能有点令人难以承受,但这是非常值得的,特别是如果您处理复杂的企业生态系统。该集成工具实际上使设置非常复杂的配置系统变得非常容易,并根据您的需求变化进行管理。

顺便说一句:一旦你掌握了它的窍门,你可能最终会想将它用于更多的用途,而不仅仅是连接字符串!

This kind of configuration issue is solved quite nicely using Enterprise Library "Shared Configuration Sources" and "Differential Configurations" (for easily switching between multiple environments, etc.).

To learn about Advanced Configuration Scenarios, try starting here:

http://msdn.microsoft.com/en-us/library/ff664552(v=pandp.50).aspx

And to integrate the Enterprise Library Configuration Tool (GUI) in Visual Studio, try here:

http://visualstudiogallery.msdn.microsoft.com/029292f0-6e66-424f-8381-3454c8222f9a

The learning curve may seem a bit overwhelming at first, but it is well worth the effort, especially if you are dealing with complex enterprise ecosystems. The integrated tool actually makes it pretty easy to set up a very sophisticated configuration system, and manage it as your requirements change.

BTW: Once you get the hang of it, you'll probably end up wanting to use it for a lot more than just your Connection Strings!

小忆控 2024-10-31 03:17:36

ConfigurationManager.OpenExeConfiguration 对我不起作用。

但是,Properties.Settings.Default. 效果很好。

The ConfigurationManager.OpenExeConfiguration didn't work for me.

But, Properties.Settings.Default.<SettingName> worked well.

就此别过 2024-10-31 03:17:36

是否可以选择从每个 Web 服务的配置中引用库的配置文件? .NET 中有一个类似 XML include 的机制:

在 app.config 中使用 XML 包含或配置引用来包含其他配置文件的设置

http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with -external-config-files.aspx

虽然您仍然需要编辑每个 web.config,但实际内容保留在一个位置。

Would it be an option to reference the library's configuration file from each web service's configuration? There is an XML include-like mechanism in .NET:

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

http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx

While you'd still need to edit each web.config, the actual content is maintained in a single place.

爱人如己 2024-10-31 03:17:36

您可以使用开源 Config.Net 库,它支持多种数据源,包括您的一个 https://github.com/ aloneguid/config

You can use the opensource Config.Net library which supports multiple sources of data, including your one https://github.com/aloneguid/config

家住魔仙堡 2024-10-31 03:17:36

您可以从托管应用程序的 web.configapp.config 读取类库的配置设置。

如果在控制台应用程序中引用类库,请将类库所需的设置放入控制台应用程序的 app.config 中(例如在 appSettings 下),并使用 System.Configuration 下的 ConfigurationManager 从类库中读取它。

如果在 Web 应用程序中引用类库,请将类库所需的设置放入 Web 应用程序的 web.config 中(例如在 appSettings 下),并使用 <代码>系统.配置。

You can read the configuration settings of the class library from the hosting application's web.config or app.config.

If the class library is referenced in a console application, put the settings, the class library needs, in the app.config of the console application (say under appSettings) and read it from the class library using ConfigurationManager under System.Configuration.

If the class library is referenced in a web application, put the settings the class library needs in the web.config of the web application (say under appSettings) and read it from the class library using ConfigurationManager under System.Configuration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文