如何在企业图书馆数据访问中使用外部配置文件中的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>
my external config:
<?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#
*我在"http://blogs.msdn.com/b/tomholl/archive/2006/04/02/entlib2externalconfig.aspx"中找到了一些帮助我的东西
这取决于您将外部配置文件放在哪里。我需要把它放在一个可以修改它的环境中。下面是部分代码:
using System.Configuration;
public class ConfigHelper
{
private const string ConfigPathString = @"{0}MyAppApp.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;
}
}