ConfigurationManager 不断获取 Machine.config 连接字符串 [英] ConfigurationManager keeps getting Machine.config connection string

查看:30
本文介绍了ConfigurationManager 不断获取 Machine.config 连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 c# 程序集,它使用 app.config 来存储其数据库连接字符串.在调试应用程序时,我注意到与数据库的连接一直失败,因为 ConfigurationManager 不断返回 machine.config 连接字符串:

I have a c# assembly that uses the app.config to store its database connection string. When debugging the application I noticed that the connection to the database kept failing because the ConfigurationManager kept returning the machine.config connection string:

数据源=.SQLEXPRESS;集成安全性;....

data source=.SQLEXPRESS; Integrated Security;....

我在 app.config 中的连接字符串之前添加了 <clear/>,它解决了我的开发机器上的问题.当我将其部署到生产环境时,问题又回来了.有人能告诉我如何停止使用 machine.config 连接字符串吗?

I added <clear/> before my connection string in the app.config and it fixed the issue on my dev machine. The problem returned when I deployed it to production. Can someone tell me how I can stop the machine.config connection string from being used?

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);

<connectionStrings>
    <clear/>
    <add name="VersionConnectionString"
     connectionString=" Data Source=localhost;Initial Catalog=VersionInfo;User ID=user;Password=password"         
     providerName="System.Data.SqlClient" />
  </connectionStrings>

更新

下面还是给我machine.config连接字符串?!

The following still gives me the machine.config connection string?!

 Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                string dllConfigData =
                    appConfig.ConnectionStrings.ConnectionStrings[0].ConnectionString;

推荐答案

在 DLL 中使用连接字符串时,您还需要将它们添加到您的 exe 的 app.config 中,并使用与设置完全相同的名称.然后,您可以更改 exe 的 .config 文件中的连接字符串,DLL 会在加载时自动选取它.

When using connection strings in a DLL, you need to add them to your exe's app.config as well, using the exact same name for the setting. Then, you can change the connection string in the exe's .config file and the DLL will pick it up automatically when loaded.

当您的数据库持久层在单独的 DLL 中实现时,这可能是您可以在 app.config 文件中使用自定义连接字符串的唯一方法.甚至不要问我研究和调试这个花了多少时间.

This is probably the only way you can have working custom connection strings in the app.config file when your DB persistence layer is implemented in a separate DLL. Don't even ask me how much time it took me to research and debug this.

这篇关于ConfigurationManager 不断获取 Machine.config 连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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