.exe 和 .dll 之间的共享配置

发布于 2024-12-03 15:51:30 字数 235 浏览 3 评论 0原文

我正在尝试在我的项目中使用 settings.settings 文件。有些值需要在 .exe 文件和各种 DLL 之间共享。我不想只是传递这些值,我想在需要时访问它们,但每个项目设置其值的名称略有不同,因此其他项目无法访问它们。

有没有办法使用 settings.settings 方法在 .exe 和 .dll 之间共享 app.config 文件的内容?或者我是否需要重新使用 ConfigurationManager 才能执行此操作?

I'm trying to work with a settings.settings file in my project. There are values that need to be shared between the .exe file and various DLLs. I'd rather not just pass these values around, I'd like to access them when I need them but each project sets up its values with slightly different names and therefore aren't reachable by the other projects.

Is there any way to share the contents of the app.config file between an .exe and a .dll using the settings.settings approach? Or do I need to go back to using ConfigurationManager in order to do this?

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

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

发布评论

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

评论(1

樱桃奶球 2024-12-10 15:51:30

只需将您的设置放入 App.config 文件中,然后从 dll 中读取它们即可。事实上,我相信这是您的 dll 查找设置/配置的唯一位置,该 dll 的本地配置将被忽略。

下面是一个快速示例,用于确保 dll 没有对应用程序的强引用。这段代码不是很好,但你明白了。

  private string GetSettingValue(string key)
  {
     string executingAssembly = Assembly.GetEntryAssembly().GetName().Name;
     string sectionName = "applicationSettings/" + executingAssembly 
                                                 + ".Properties.Settings";
     ClientSettingsSection section =
            (ClientSettingsSection)ConfigurationManager.GetSection(sectionName);

     // add null checking etc
     SettingElement setting = section.Settings.Get(key); 
     return setting.Value.ValueXml.InnerText;
  }

或者,使用具有共享设置的通用 dll 并从需要共享配置的每个程序集获取依赖项。这要干净得多。

Just put your settings in the App.config file, and read them from your dll. In fact I believe it's the only place your dll will look for settings/config, local config for the dll is ignored.

Here's a quick example to ensure the dll has no strong references to the application. This code isn't great but you get the idea.

  private string GetSettingValue(string key)
  {
     string executingAssembly = Assembly.GetEntryAssembly().GetName().Name;
     string sectionName = "applicationSettings/" + executingAssembly 
                                                 + ".Properties.Settings";
     ClientSettingsSection section =
            (ClientSettingsSection)ConfigurationManager.GetSection(sectionName);

     // add null checking etc
     SettingElement setting = section.Settings.Get(key); 
     return setting.Value.ValueXml.InnerText;
  }

Alternatively have a common dll with the shared settings and take a dependency from each assembly that needs to share the config. This is far cleaner.

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