使用自定义配置部分与企业库数据访问

时间:2014-05-26 20:29:21

标签: c# .net connection-string enterprise-library

如何使用Enterprise Library Data Access中的外部配置文件中的connectionString?

我的app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="custom.configuration.server" type="Custom.Framework.Core.Configuration.Server.CustomConfigurationServerSection, Custom.Framework.Core"/>
  </configSections>
  <custom.configuration.server configSource="custom.configuration.server.config"/>
</configuration>

我的外部配置:

<?xml version="1.0" encoding="utf-8" ?>
<custom.configuration.server>
  <products>
    <add name="Product1">
      <enterprises>
        <add enterpriseKey="1" enterprise="Enterprise1">
          <databases>
            <add database="test" connectionString="Data Source=server;Initial Catalog=Enterprise1Test;Integrated Security=True" />
            <add database="development" connectionString="Data Source=server;Initial Catalog=Enterprise1Dvp;Integrated Security=True" />
          </databases>
        </add>
        <add enterpriseKey="2" enterprise="Enterprise2">
          <databases>
            <add database="test" connectionString="Data Source=server;Initial Catalog=Enterprise2Test;Integrated Security=True" />
            <add database="development" connectionString="Data Source=server;Initial Catalog=Enterprise2Dvp;Integrated Security=True" />
          </databases>
        </add>
      </enterprises>
    </add>
  </products>
</custom.configuration.server>

我的样本电话:

public void TestMethod1()
        {
            using (var customDatabase = new CustomDatabase("development"))
            {

            }
        }

注意:Windows 8.1,Visual Studio 2013,Net Framework 4.5,Enterprise Library 6.0,C#

*我在&#34; http://blogs.msdn.com/b/tomholl/archive/2006/04/02/entlib2externalconfig.aspx&#34;

中找到了帮助我的东西

1 个答案:

答案 0 :(得分:0)

这取决于您放置外部配置文件的位置。我需要将它放在我可以修改它的环境中。以下是代码的一部分:

using System.Configuration;

public class ConfigHelper
{
    private const string ConfigPathString = @"{0}\MyApp\App.config";

    private string ConfigPath
    {
        get { return String.Format( ConfigPathString, System.Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData ) ); }
    }

    private Configuration Config
    {
        get
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = ConfigPath;

            return ConfigurationManager.OpenMappedExeConfiguration( fileMap, ConfigurationUserLevel.None );
        }
    }

    public string ReadConString()
    {
        Configuration cfg = Config;
        return cfg.ConnectionStrings.ConnectionStrings[DefaultConnectionStringKey].ConnectionString;
    }
}