如何让 .NET 类库读取自己的配置文件? [英] How can I make a .NET class library read its own configuration file?

查看:18
本文介绍了如何让 .NET 类库读取自己的配置文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET 类库,它提供了一组由多个 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.

遗憾的是,.NET 无法轻松读取 DLL 的 app.config 文件.唯一简单"的解决方案是将连接字符串存储在每个 Web 服务配置文件中,这完全是胡说八道.

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.

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

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?

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

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.

推荐答案

我认为您正在寻找:

ConfigurationManager.OpenExeConfiguration(string exePath)

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

返回一个 Configuration 对象.ConfigurationManager 上的 MSDN 文档

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

Try this question for how to get the DLL path.

这篇关于如何让 .NET 类库读取自己的配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆