EnterpriseLibrary数据访问应用程序块重定向部分无法找到默认的数据库 [英] EnterpriseLibrary Data Access Application Block redirect Section can't find default database

查看:301
本文介绍了EnterpriseLibrary数据访问应用程序块重定向部分无法找到默认的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到处理的数据重定向的部分EnterpriseLibrary数据访问应用程序块?



我不喜欢有从app.config中删除数据库的定义并放置在一个独立的database.config文件。



我尝试做我的logging.config做同样的方式和exception.config文件,但我可以' 。弄不明白工作

 使用Microsoft.Practices.EnterpriseLibrary.Common.Configuration;使用Microsoft.Practices.EnterpriseLibrary.Data 
;
使用Microsoft.Practices.EnterpriseLibrary.Data.Sql;
使用Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
使用Microsoft.Practices.EnterpriseLibrary.Logging;
使用系统;
使用System.Data这;

命名空间entlib6
{
类节目
{
静态无效的主要(字串[] args)
{

IConfigurationSource源= ConfigurationSourceFactory.Create();

LogWriterFactory logwriterFactory =新LogWriterFactory(源);
VAR日志写= logwriterFactory.Create();
Logger.SetLogWriter(日志写进程);

变种exceptionPolicyFactory =新ExceptionPolicyFactory(源);
VAR exceptionManager = exceptionPolicyFactory.CreateManager();
ExceptionPolicy.SetExceptionManager(exceptionManager);

DatabaseProviderFactory厂=新DatabaseProviderFactory(源);
DatabaseFactory.SetDatabaseProviderFactory(工厂,FALSE);


//测试日志程序块
logWriter.Write(这是一条测试);

//测试异常块

{
抛出新NotImplementedException();
}
赶上(例外的例外)
{

异常newException;

VAR rethrowNewException = ExceptionPolicy.HandleException(例外,政策,出newException);

如果(rethrowNewException)
扔newException;
}

//测试数据块失败,并低于
// System.InvalidOperationException了未处理的
//消息=配置文件没有定义默认的错误代码数据库。
VAR sqlServerDb = DatabaseFactory.CreateDatabase()作为SqlDatabase;使用
(IDataReader的读卡器= sqlServerDb.ExecuteReader(CommandType.Text,SELECT TOP 1 * FROM Production.Product))
{
,而(reader.Read())
{
的for(int i = 0; I< reader.FieldCount;我++)
{
Console.WriteLine({0} = {1},reader.GetName(I) ,读者[I]);
}
Console.WriteLine();
}
}
}
}
}

我揭露的配置文件位置如下:

 < XML版本=1.0编码=UTF- 8>?; 
<结构>
< configSections>
<节名称=enterpriseLibrary.ConfigurationSourceTYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection,Microsoft.Practices.EnterpriseLibrary.CommonrequirePermission =真/>
< / configSections>
< enterpriseLibrary.ConfigurationSource selectedSource =SystemConfiguration>
<来源和GT;
<添加名称=SystemConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource,Microsoft.Practices.EnterpriseLibrary.Common/>
<添加名称=ExceptionConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource,Microsoft.Practices.EnterpriseLibrary.Common文件路径=exception.config/>
<添加名称=LoggingConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource,Microsoft.Practices.EnterpriseLibrary.Common文件路径=logging.config/>
<添加名称=PolicyConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource,Microsoft.Practices.EnterpriseLibrary.Common文件路径=policy.config/>
<添加名称=DatabaseConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource,Microsoft.Practices.EnterpriseLibrary.Common文件路径=database.config/>
< /来源>
< redirectSections>
<添加SOURCENAME =ExceptionConfigurationNAME =exceptionHandling/>
<添加SOURCENAME =LoggingConfigurationNAME =loggingConfiguration/>
<添加SOURCENAME =PolicyConfigurationNAME =policyConfiguration/>
<添加SOURCENAME =DatabaseConfigurationNAME =databaseConfiguration/>
< / redirectSections>
< /enterpriseLibrary.ConfigurationSource>
<&启动GT;
< supportedRuntime版本=V4.0SKU =.net框架,版本= V4.5/>
< /启动>
< /结构>

< XML版本=1.0编码=UTF-8>?;
<结构>
< configSections>
<节名称=dataConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,Microsoft.Practices.EnterpriseLibrary.DatarequirePermission =真/>
< / configSections>
< dataConfiguration defaultDatabase =DefaultConnection/>
<&是connectionStrings GT;
<添加名称=DefaultConnection的connectionString =数据源=(的LocalDB)\v11.0;初始目录= AdventureWorks2008R2;集成安全性=真的providerName =System.Data.SqlClient的/>
< /&是connectionStrings GT;
< /结构>


< XML版本=1.0编码=UTF-8>?;
<结构>
< configSections>
<节名称=loggingConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings,Microsoft.Practices.EnterpriseLibrary.LoggingrequirePermission =真/>
< / configSections>
< loggingConfiguration NAME =tracingEnabled =真defaultCategory =常规>
<&听众GT;
<添加名称=滚动平面文件跟踪监听器类型=Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener,Microsoft.Practices.EnterpriseLibrary.Logging
listenerDataType =Microsoft.Practices。 EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData,Microsoft.Practices.EnterpriseLibrary.Logging
格式化=文本格式化/>
< /听众>
<格式化>
<加上TYPE =Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter,Microsoft.Practices.EnterpriseLibrary.Logging
模板=时间戳:{时间戳} {}换行和放大器; #xA;消息:{消息} {换行符}&放大器; #xA;类别:{类别} {换行符}&放大器; #xA;优先级:{优先权} {换行符}&放大器; #xA;事件ID:{事件ID} {换行符}&安培;# XA;严重性:{严重} {换行符}&放大器; #xA;标题是:{title} {换行符}&放大器; #xA;机:{LOCALMACHINE} {换行符}&放大器; #xA;应用程序域:{localAppDomain} {换行符} &安培; #xA;的ProcessID:{localProcessId} {换行符}&放大器; #xA;进程名称:{localProcessName} {换行符}&放大器; #xA;螺纹名称:{threadName} {换行符}&放大器; #xA;的Win32的ThreadId:{ win32ThreadId} {}换行和放大器; #xA;扩展属性:{字典({}键 - {值} {}换行符)}
NAME =文本格式化/>
< /格式化>
< categorySources>
<添加switchValue =全部NAME =常规>
<&听众GT;
<添加名称=滚动平面文件跟踪监听器/>
< /听众>
< /添加>
< / categorySources>
< specialSources>
< allEvents switchValue =全部NAME =所有事件/>
< notProcessed switchValue =全部NAME =未处理类别/>
<错误switchValue =全部NAME =记录错误和放大器;放大器;警告>
<&听众GT;
<添加名称=滚动平面文件跟踪监听器/>
< /听众>
< /错误>
< / specialSources>
< / loggingConfiguration>
< /结构>


< XML版本=1.0编码=UTF-8>?;
<结构>
< configSections>
<节名称=exceptionHandlingTYPE =Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings,Microsoft.Practices.EnterpriseLibrary.ExceptionHandlingrequirePermission =真/>
< / configSections>
< exceptionHandling>
< exceptionPolicies>
<添加名称=政策>
< exceptionTypes>
<添加名称=NotImplementedExceptionTYPE =System.NotImplementedException,mscorlib中
postHandlingAction =无>
<&的ExceptionHandlers GT;
<添加名称=记录异常处理程序TYPE =Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler,Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging
logCategory =常规事件ID = 100严重性=错误称号=企业库异常处理
formatterType =Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter,Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
优先=0 />
< /&的ExceptionHandlers GT;
< /添加>
< / exceptionTypes>
< /添加>
< / exceptionPolicies>
< / exceptionHandling>
< /结构>


解决方案

有几种方法可以有不同的配置文件:




  • redirectedSection

  • 内置.NET configSource

  • FileConfigurationSource



redirectedSections方法



我觉得在你的配置错误的是。你没有重定向connectionStrings节



的app.config:

 <?XML版本=1.0编码=UTF-8>?; 
<结构>
< configSections>
<节名称=enterpriseLibrary.ConfigurationSourceTYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection,Microsoft.Practices.EnterpriseLibrary.Common,版本6.0.0.0 =文化=中性公钥= 31bf3856ad364e35 requirePermission =真/>
< / configSections>
< enterpriseLibrary.ConfigurationSource selectedSource =系统配置源>
<来源和GT;
<添加名称=系统配置源TYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource,Microsoft.Practices.EnterpriseLibrary.Common,版本6.0.0.0 =文化=中性公钥= 31bf3856ad364e35 />
<添加名称=基于文件的配置源TYPE =Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource,Microsoft.Practices.EnterpriseLibrary.Common,版本6.0.0.0 =文化=中性公钥= 31bf3856ad364e35
文件路径=data.config/>
< /来源>
< redirectSections>
<添加SOURCENAME =基于文件的配置源NAME =dataConfiguration/>
<添加SOURCENAME =基于文件的配置源NAME =是connectionStrings/>
< / redirectSections>
< /enterpriseLibrary.ConfigurationSource>
<&启动GT;
< supportedRuntime版本=V4.0SKU =.net框架,版本= V4.5/>
< /启动>
< /结构>



data.config:



 <?XML版本=1.0编码=UTF-8>?; 
<结构>
< configSections>
<节名称=dataConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,Microsoft.Practices.EnterpriseLibrary.Data,版本6.0.0.0 =文化=中性公钥= 31bf3856ad364e35requirePermission =真/>
< / configSections>
< dataConfiguration defaultDatabase =ABC/>
<&是connectionStrings GT;
<添加名称=ABC的connectionString =ABC的providerName =System.Data.SqlClient的/>
< /&是connectionStrings GT;
< /结构>



引导代码:



  DatabaseProviderFactory厂=新DatabaseProviderFactory(新SystemConfigurationSource()); 
DatabaseFactory.SetDatabaseProviderFactory(工厂,FALSE);



configSource方法



使用内置的在.NET configSource到configSections重定向到一个外部文件



的app.config:

 <?XML版本=1.0编码=UTF-8>?; 
<结构>
< configSections>
<节名称=dataConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,Microsoft.Practices.EnterpriseLibrary.Data,版本6.0.0.0 =文化=中性公钥= 31bf3856ad364e35requirePermission =真/>
< / configSections>
< dataConfiguration configSource =data.config/>
<是connectionStrings configSource =connections.config/>
<&启动GT;
< supportedRuntime版本=V4.0SKU =.net框架,版本= V4.5/>
< /启动>
< /结构>



connections.config:



 <?XML版本=1.0编码=UTF-8>?; 
<&是connectionStrings GT;
<添加的connectionString =ABCNAME =ABC的providerName =System.Data.SqlClient的/>
< /&是connectionStrings GT;



data.config:



 <?XML版本=1.0编码=UTF-8>?; 
< dataConfiguration defaultDatabase =ABC/>



引导代码:



  DatabaseProviderFactory厂=新DatabaseProviderFactory(); 
DatabaseFactory.SetDatabaseProviderFactory(工厂,FALSE);



FileConfigurationSource方法



使用一个FileConfigurationSource在引导加载相应的配置文件。

 <$ C $:因为我们将在启动时的的app.config 不需要任何企业库配置直接加载FileConfigurationSource C><?XML版本=1.0编码=UTF-8>?; 
<结构>
<&启动GT;
< supportedRuntime版本=V4.0SKU =.net框架,版本= V4.5/>
< /启动>
< /结构>



data.config:



 <?XML版本=1.0编码=UTF-8>?; 
<结构>
< configSections>
<节名称=dataConfigurationTYPE =Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,Microsoft.Practices.EnterpriseLibrary.Data,版本6.0.0.0 =文化=中性公钥= 31bf3856ad364e35requirePermission =真/>
< / configSections>
< dataConfiguration defaultDatabase =ABC/>
<&是connectionStrings GT;
<添加名称=ABC的connectionString =ABC的providerName =System.Data.SqlClient的/>
< /&是connectionStrings GT;
< /结构>



引导代码:



  FileConfigurationSource configSource =新FileConfigurationSource(data.config); 
DatabaseProviderFactory厂=新DatabaseProviderFactory(configSource);

如果你想修改配置文件加载的能力(即data.config),那么您可以使用一个appSetting指定要加载的文件。


How can I to get working the Data redirected section for EnterpriseLibrary Data Access Application Block?

I would do like to have the definitions for databases removed from app.config and placed on a standalone database.config file.

I try to do the same way I am doing with the logging.config and and exception.config files but I can't get it work.

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.Data;

namespace entlib6
{
    class Program
    {
        static void Main(string[] args)
        {

            IConfigurationSource source = ConfigurationSourceFactory.Create();

            LogWriterFactory logwriterFactory = new LogWriterFactory(source);
            var logWriter = logwriterFactory.Create();
            Logger.SetLogWriter(logWriter);

            var exceptionPolicyFactory = new ExceptionPolicyFactory(source);
            var exceptionManager = exceptionPolicyFactory.CreateManager();
            ExceptionPolicy.SetExceptionManager(exceptionManager);

            DatabaseProviderFactory factory = new DatabaseProviderFactory(source);
            DatabaseFactory.SetDatabaseProviderFactory(factory, false);


            // Test Logging Block
            logWriter.Write("This a test");

            // Test Exception block
            try
            {
                throw new NotImplementedException();
            }
            catch (Exception exception)
            {

                Exception newException;

                var rethrowNewException = ExceptionPolicy.HandleException(exception, "Policy", out newException);

                if (rethrowNewException)
                    throw newException;
            }

            // Test Data Block fails with error code below
            //  System.InvalidOperationException was unhandled
            //  Message=The configuration file does not define a default database.
            var sqlServerDb = DatabaseFactory.CreateDatabase() as SqlDatabase;
            using (IDataReader reader = sqlServerDb.ExecuteReader(CommandType.Text, "SELECT TOP 1 * FROM Production.Product"))
            {
                while (reader.Read())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        Console.WriteLine("{0} = {1}", reader.GetName(i), reader[i]);
                    }
                    Console.WriteLine("");
                }
            }
        }
    }
}

I expose the configurations files here below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common" requirePermission="true" />
  </configSections>
  <enterpriseLibrary.ConfigurationSource selectedSource="SystemConfiguration">
    <sources>
      <add name="SystemConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" />
      <add name="ExceptionConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="exception.config" />
      <add name="LoggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="logging.config" />
      <add name="PolicyConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="policy.config" />
      <add name="DatabaseConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common" filePath="database.config" />
    </sources>
    <redirectSections>
      <add sourceName="ExceptionConfiguration" name="exceptionHandling" />
      <add sourceName="LoggingConfiguration" name="loggingConfiguration" />
      <add sourceName="PolicyConfiguration" name="policyConfiguration" />
      <add sourceName="DatabaseConfiguration" name="databaseConfiguration" />
    </redirectSections>
  </enterpriseLibrary.ConfigurationSource>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" requirePermission="true" />
      </configSections>
      <dataConfiguration defaultDatabase="DefaultConnection" />
      <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=AdventureWorks2008R2;Integrated Security=True" providerName="System.Data.SqlClient" />
      </connectionStrings>
    </configuration>


    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging" requirePermission="true" />
      </configSections>
      <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
        <listeners>
          <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging"
              listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging"
              formatter="Text Formatter" />
        </listeners>
        <formatters>
          <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging"
              template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
              name="Text Formatter" />
        </formatters>
        <categorySources>
          <add switchValue="All" name="General">
            <listeners>
              <add name="Rolling Flat File Trace Listener" />
            </listeners>
          </add>
        </categorySources>
        <specialSources>
          <allEvents switchValue="All" name="All Events" />
          <notProcessed switchValue="All" name="Unprocessed Category" />
          <errors switchValue="All" name="Logging Errors &amp; Warnings">
            <listeners>
              <add name="Rolling Flat File Trace Listener" />
            </listeners>
          </errors>
        </specialSources>
      </loggingConfiguration>
    </configuration>


    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" requirePermission="true" />
      </configSections>
      <exceptionHandling>
        <exceptionPolicies>
          <add name="Policy">
            <exceptionTypes>
              <add name="NotImplementedException" type="System.NotImplementedException, mscorlib"
                postHandlingAction="None">
                <exceptionHandlers>
                  <add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging"
                    logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
                    formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
                    priority="0" />
                </exceptionHandlers>
              </add>
            </exceptionTypes>
          </add>
        </exceptionPolicies>
      </exceptionHandling>
    </configuration>

解决方案

There are a few ways to have separate configuration files:

  • redirectedSection
  • built-in .NET configSource
  • FileConfigurationSource

redirectedSections Approach

I think the error in your configuration is that you haven't redirected the connectionStrings section.

app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <enterpriseLibrary.ConfigurationSource selectedSource="System Configuration Source">
    <sources>
      <add name="System Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <add name="File-based Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        filePath="data.config" />
    </sources>
    <redirectSections>
      <add sourceName="File-based Configuration Source" name="dataConfiguration" />
      <add sourceName="File-based Configuration Source" name="connectionStrings" />
    </redirectSections>
  </enterpriseLibrary.ConfigurationSource>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

data.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <dataConfiguration defaultDatabase="abc" />
  <connectionStrings>
    <add name="abc" connectionString="abc" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Bootstrap code:

DatabaseProviderFactory factory = new DatabaseProviderFactory(new SystemConfigurationSource());
DatabaseFactory.SetDatabaseProviderFactory(factory, false);

configSource Approach

Use the built-in .NET configSource to redirect configSections to an external file.

app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <dataConfiguration configSource="data.config" />
  <connectionStrings configSource="connections.config" />
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

connections.config:

<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
  <add connectionString="abc" name="abc" providerName="System.Data.SqlClient"/>
</connectionStrings>

data.config:

<?xml version="1.0" encoding="utf-8" ?>
<dataConfiguration defaultDatabase="abc" />

Bootstrap Code:

DatabaseProviderFactory factory = new DatabaseProviderFactory();
DatabaseFactory.SetDatabaseProviderFactory(factory, false);

FileConfigurationSource Approach

Use a FileConfigurationSource at bootstrap to load the appropriate configuration files. Since we will load the FileConfigurationSource directly at startup the app.config does not need any Enterprise Library configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

data.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <dataConfiguration defaultDatabase="abc" />
  <connectionStrings>
    <add name="abc" connectionString="abc" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Bootstrap code:

FileConfigurationSource configSource = new FileConfigurationSource("data.config");
DatabaseProviderFactory factory = new DatabaseProviderFactory(configSource);

If you wanted the ability to modify the config file to load (i.e. "data.config") then you could use an appSetting to specify the file to load.

这篇关于EnterpriseLibrary数据访问应用程序块重定向部分无法找到默认的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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