【IT168技术文档】
我们知道在Enterprise Library1.1中对于每一个应用程序块都有一个对应的配置文件,而在Enterprise Library2.0中却把所有的配置信息都放在了应用程序配置文件(App.config或Web.config)中,在2.0下,我们如何使用外部配置文件?如何为每个应用程序块创建对应的配置文件?
主要内容
1.不使用外部配置文件
2.使用不同的ConfigurationSource
3.使用多个ConfigurationSource
4.使用.NET的configSource特性
一.不使用外部配置文件
我们先来看一个简单的使用Enterprise Library的例子,在这个示例中,使用了企业库的Data Access Application Block和 Excepiton Handling Application Block。
使用Enterprise Library Configuration配置之后,App.config文件如下: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; } } } }
<?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>