在 Enterprise Library 1.1 中,每個應用程式區塊都有對應的獨立設定檔;但到了 2.0 版,所有組態資訊預設都集中在應用程式設定檔(App.config 或 Web.config)中。若不想讓大量自訂設定與企業庫組態混雜,該如何使用外部設定檔?本文整理 Tom Hollander 提供的幾種可行方案。
configSource 屬性先看一個簡單範例,使用 Data Access Application Block 與 Exception Handling Application Block:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
namespace EntLibConfig
{
class Program
{
static void Main(string[] args)
{
try
{
Database db = DatabaseFactory.CreateDatabase("EntLibInstance");
db.ExecuteNonQuery("ProcName");
}
catch (Exception ex)
{
if (ExceptionPolicy.HandleException(ex, "Event Policy"))
throw;
}
}
}
}
經由 Enterprise Library Configuration Tool 設定後,App.config 內容如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
</configSections>
<exceptionHandling>
<exceptionPolicies>
<add name="Event Policy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException" name="Exception">
<exceptionHandlers>
<add exceptionMessage="This is a test!" replaceExceptionType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionHandlingException, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
name="Replace Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
<dataConfiguration defaultDatabase="EntLibInstance" />
<connectionStrings>
<add name="EntLibInstance" connectionString="Server=.\SQLEXPRESS;Integrated Security=SSPI;Database=Northwind;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
可以看到所有組態都集中在應用程式設定檔中。若混合大量自訂設定會顯得混亂,後續章節將介紹如何拆分至外部檔案。