EnterpriseLibrary数据访问应用程序块重定向部分无法找到默认数据库

本文关键字:数据库 默认 重定向部 访问 数据 应用 应用程序 程序块 EnterpriseLibrary | 更新日期: 2023-09-27 18:03:08

我怎么能得到工作的数据重定向部分为EnterpriseLibrary数据访问应用程序块?

我想有数据库的定义从app.config删除,并放置在一个独立的数据库。配置文件。

我尝试用与日志记录相同的方式做。配置and和exception。配置文件,但我不能让它工作。

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("");
                }
            }
        }
    }
}

我在下面公开配置文件:

<?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>

EnterpriseLibrary数据访问应用程序块重定向部分无法找到默认数据库

有几种方法可以拥有单独的配置文件:

  • redirectedSection
  • 内置。net configSource
  • FileConfigurationSource

redirectedSections方法

我认为您配置中的错误是您没有重定向connectionStrings部分。

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>

引导代码:

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

configSource方法

使用内置的。net configSource将configSections重定向到外部文件。

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" />

引导代码:

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

FileConfigurationSource方法

在引导时使用fileconconfigurationsource来加载适当的配置文件。因为我们将在启动应用程序时直接加载fileconconfigurationsource。config不需要任何企业库配置:

<?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>

引导代码:

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

如果你想要修改要加载的配置文件(例如:"data.config"),那么你可以使用appSetting来指定要加载的文件。

相关文章: