C# 读取 Spring 框架连接字符串

C# Read Spring Framework Connection String

这里的许多其他问题都集中在 System.Configuration.ConfigurationManager... 的使用上 对于我的问题,我需要从 Spring 中提取连接字符串对象以确定连接到的服务器并删除任何 banners/warnings 使用应用程序的测试版本。这个想法是 如果应用程序连接到 "sp1-...",则该应用程序是生产版本。

如何读取嵌套在 App.config xml 上下文中的对象?请注意,它存在于 Hibernate 对象之外,因此(在我看来)必须存储在 Spring 库变量中。

下面是我的 App.config 应用程序的一部分。

...
<spring>
  <context>
    <resource uri="config://spring/objects" />
  </context>
  <parsers>
    <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data" />
    <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data" />
  </parsers>
  <objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.net/tx" xmlns:db="http://www.springframework.net/database">
    <db:provider id="DbProvider" provider="SqlServer-2.0" connectionString="Data Source=st1-dskdb;Integrated Security=true;Database=AmericaMe_Test;" />
    <!-- HIBERNATE OBJECT -->
    <object id="MySessionFactory" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate12">
      <property name="ExposeTransactionAwareSessionFactory" value="true" />
      <property name="DbProvider" ref="DbProvider" />
...

如果给定一个正常的 App.config 设置,这是我执行此操作的方式:

// Remove the "WARNING Test Version" Label if not the production server (sp1...)
if (System.Configuration.ConfigurationManager.ConnectionStrings[0].ConnectionString.ToLower().Contains("sp1"))
{
    WarningBox.Visible = false;
    WarningLabel.Visible = false;
    MainTabController.Dock = DockStyle.Fill;
}

EDIT 看来 XMLReader 方向是唯一的出路。在我看来有点野蛮,但这是我实现的有效代码:

// Remove the "WARNING Test Version" Label if not the production server (sp1...)
using (System.Xml.XmlReader appConfigReader = System.Xml.XmlReader.Create("AmericaMe.exe.config"))
{
    while (appConfigReader.Read())
    {
        string appConfigLine = appConfigReader.Name;

        if (appConfigLine.Contains("db:provider"))
        {
            string server = appConfigReader.GetAttribute(2);
            if (server.Contains("Source=sp1-"))
            {
                WarningBox.Visible = false;
                WarningLabel.Visible = false;
                MainTabController.Dock = DockStyle.Fill;
            }
            break;
        }
    }
}

这对于 ConfigurationManager 是不可能的,因为它只能理解 web.config 文件中添加的连接字符串部分。

您可能需要使用 XmlReader 手动解析 xml。

有关解析 xml 的详细信息,请参阅 link