[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview

在过去的半年里,定期或者不定期地写点东西已经成为了我的一种习惯。可是最近两个月来一直忙于工作的事情一直足够的时间留给自己,虽然给自己列了很长一串写作计划,可是心有余而力不足。这一段工作主要是帮助公司开发一套分布式的开发框架,对一些技术和设计方法有了一些新的认识。这两天的工作主要是如何把Enterprise Library V3.1PIABPolicy Injection Application Block)引入到我们自己的框架中,为次对PIAB进行了一些研究,借此机会与大家一起分享。

  1. Part I: PIAB Overview
  2. Part II: PIAB设计和实现原理
  3. Part IIIPIAB扩展-如何创建Custom CallHandler

一、Business Logic Infrastructure Logic的分离

对于任何一个企业级应用的开发人员来说,他们编写的代码不仅仅是处理单纯的业务逻辑,同时还需要处理很多的非业务方面的逻辑,比如:CachingTransaction EnlistAuthorizationAuditingException HandlingLoggingValidation甚至是Performance Counter。我习惯把这些非业务逻辑成为Infrastructure Logic。由于这些Infrastructure Logic通常根据具体的需求注入的具体的业务逻辑的执行中,所以又被更多地成为Crosscutting Concern

如果按照传统的OO的编程方式,我们通常将这些Business ConcernCrosscutting Concern糅合在一起,从而导致了某种意义的紧耦合。这种紧耦合在一个大型的企业级应用可能是会给应用的可扩展性带来致命的影响。所以必须以某种方式实现Business ConcernCrosscutting Concern的分离,这通常是AOP实现的目标。

举个简单的例子,我们现在有如下一个简单的订单处理操作,可能具体的业务逻辑很简单。但是此操作面临的非业务逻辑可能有很多。比如:· 在处理之前进行Authorization,确定当前的用户是否具有此操作的权限。
· Auditing,记录处理的用户、处理时间等等。
·
Transaction Enlist,将所有Data Access操作纳入同一个Transaction,保证数据的一致性。
· 进行Exception Handling
· 如果出现异常,记录日志。

上面的这些可以体现在线面的Code中:

public void ProcessOrder(Order order)

{

Authorize();

Audit();

using (TransactionScope scope = new TransactionScope())

{

try

{

OrderDataAccess();
}

catch (Exception ex)

{

HandleExceptoin(ex);

Log();

}

}
}

可以看到上面这么多行代码中,和业务相关的就一行而已。虽然对这些非业务逻辑的实现通常通过调用一个封装好的方法或者组件完成,你往往只需要Copy Paste就可以了,但是将如此众多的Infrastructure LogicBusiness Logic按照这样的方式组合在一起有很多的隐患。

  • 首先,将一些公共的Source code进行大规模的复制不能保证其同一性和正确性。我个人觉得,对于一个程序原来说,如果你频繁地使用到Ctrl + CCtrl + V,你应该想到你的代码需要重构。
  • 其次,Infrastructure LogicBusiness Logic这种耦合性导致对Infrastructure Logic的变动将获导致Source Code的改变。
  • 此外,这样的编程方式增加了程序员的压力,可能对于一个相对Junior的程序员来说,可能根本不知道这个Infrastructure Logic的具体作用何在,而实际上对于最终的程序员来讲,这些应该是对他们透明的。

所以我们需要寻求某种方式将这些Infrastructure Logic注入到某个具体的操作中,而不需要将所有的逻辑实现在具体的方法定义中。比如:你可以通过配置文件进行配置,你也可以通过添加Attribute一声明的方式来实现。而这一切都可以通过Enterprise LibraryPIAB来实现。

二、PIABPolicy Injection Application BlockOverview

PIABEnterprise Library 3.0中被引入(注意:不要把PIABDIAB混淆,DIAB-Dependence Injection Application Block将在Enterprise Library 4.0中被引入,个人觉得这将又是一个具有重大意义的AB,它的使用将会极大的减轻模块或组件的依赖关系,在Software Factory中已经有了广泛的应用)。PIAB提供了一种简单而有效的方式是你能够将你所需的非业务逻辑的Crosscutting concern注入到的某个方法的Invocation stack中。比如可以在方法的调用前注入Auditing的执行,在成功调用后执行Transaction commit的调用,在出现异常时进行Exception Handling的处理。

对于PIAB来说,Policy的意思是:“将对应的处理操作注入到对应的方法调用”。这实际上包含两方面的内容:要注入怎样的处理操作和如何与具体的方法匹配。前者封装在一个称作CallHandler的对象中,而匹配关系通过另一个称作MatchingRule的对象来表现。所以可以说Policy= CallHandler+MatchingRule

PIAB给我们提供了很多系统自定义CallHandler,在一般情况下它能满足我们绝大部分的需求,比如:

  • Enterprise Library Security Application BlockAuthorization来实现。
  • CachingCallHandler:将方法返回值作为Value、参数列表作为Key存入Cache,如果下次出现相同参数列表的调用,则直接将Cache中的值返回,从而免去了再次执行方法对性能的影响。像一般的Cache处理一样,你也可以设置Cache的过期时间。
  • ExceptionCallHandler:通过调用Enterprise Library Exception Handing Application Block实现对一异常处理的支持。
  • LogCallHandler:通过调用Enterprise Library Logging Application Block进行日志的处理。
  • ValidationCallHandler:进行参数的验证等功能,该CallHandler依赖于Enterprise Library Validation Application Block
  • PerformanceCounterCallHandler

至于MatchingRule,他实际上是定义了一种如何将CallHander和对应的Method进行匹配的规则。同样的,一系列的MatchingRule被定义出来,比如:基于AssemblyMatchingRuleCallHandler匹配到某个Assembly的所有对象上面;基于Custom AttributeMatchingRule通过声明在某个元素上的某个Attribute进行匹配。此外还有基于NameSpaceMethod Signature、等等的MatchingRule

如何现有的CallHandlerMatchingRule不能满足你具体的要求,你还可以定义Custom CallHandler或者 Custom MatchingRule。在后续的部分将会介绍一个完整的定义Custom CallHandler的例子。

三、Get Started

经过上面对PIAB的介绍,我想大家对PIAB使用的目标又一个简单的认识,为了加深大家的映像,在本节中,我们做一个简单的Walkthrough,做一个简单的使用PIAB的例子。在这个例子通过PIAB实现两个主要的功能:CachingLogging。为了简单起见,我们使用一个Console Application来实现这样一个例子。我们假设的一个场景时处理一个订单并将处理后的订单返回。

Step I创建一个Console Application,并添加下面连个Dll Reference.

  • Microsoft.Practices.EnterpriseLibrary.PolicyInjection
  • Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers

Step II: 编写Order Processing的代码:

public class OrderProcessor:MarshalByRefObject

{

public Order Process(Order order)

{

Console.WriteLine("OrderProcessor.Process() is invocated!");

return order;

}

}

public class Order

{ }

至于为什么要继承MarshalByRefObject将会在后面对PIAB的实现原理中介绍。将对OrderProcessor的调用写在Main()。

static void Main(string[] args)

{

OrderProcessor processor = PolicyInjection.Create<OrderProcessor>();

Order order = new Order();

processor.Process(order);

processor.Process(order);
}

Step III:创建app.config,并通过Enterprise Library Configuration Console进行配置:

1、添加一个Logging Application Block

[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview

2、 按照相同的方式添加一个Policy Injection Application Block,然后再PIAB节点添加一个Policy。在该Policy下的Match Rules节点下创建一个Method Name Matching Rule (该MatchingRule根据Method name进行CallHandler的匹配)。对该MatchingRule进行如下的配置:

[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
那么该
PolicyCallHandler将会自动应用到Method nameProcess的方法上。

3、 Policy下的Handlers节点添加两个CallHandler:Caching HandlerLogging Handler。保持Caching Handler的默认配置,按如下进行Loging Handler的配置:

[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview

通过上面的配置,我们将会得到如下的Configuration

[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview[原创]Enterprise Library Policy Injection Application Block 之一: PIAB OverviewConfiguration
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview<configuration>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<configSections>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<sectionname="policyInjection"type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration.PolicyInjectionSettings,Microsoft.Practices.EnterpriseLibrary.PolicyInjection,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<sectionname="loggingConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings,Microsoft.Practices.EnterpriseLibrary.Logging,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</configSections>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<policyInjection>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<policies>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addname="Policy">
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<matchingRules>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addtype="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.MemberNameMatchingRule,Microsoft.Practices.EnterpriseLibrary.PolicyInjection,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewname
="MemberNameMatchingRule">
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<matches>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addmatch="Process"ignoreCase="false"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</matches>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</add>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</matchingRules>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<handlers>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addexpirationTime="00:05:00"type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.CachingCallHandler,Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewname
="CachingHandler"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addlogBehavior="After"beforeMessage="=================End================="
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB OverviewafterMessage
="================Begin================"eventId="0"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB OverviewincludeParameterValues
="true"includeCallStack="true"includeCallTime="true"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewpriority
="-1"severity="Information"type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.LogCallHandler,Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewname
="LoggingHandler">
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<categories>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addname="Audit"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</categories>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</add>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</handlers>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</add>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</policies>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</policyInjection>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<loggingConfigurationname="LoggingApplicationBlock"tracingEnabled="true"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB OverviewdefaultCategory
="General"logWarningsWhenNoCategoriesMatch="true">
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<listeners>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addsource="EnterpriseLibraryLogging"formatter="TextFormatter"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewlog
="Application"machineName=""listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData,Microsoft.Practices.EnterpriseLibrary.Logging,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB OverviewtraceOutputOptions
="None"type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener,Microsoft.Practices.EnterpriseLibrary.Logging,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewname
="FormattedEventLogTraceListener"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</listeners>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<formatters>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addtemplate="Timestamp:{timestamp} Message:{message} Category:{category} Priority:{priority} EventId:{eventid} Severity:{severity} Title:{title} Machine:{machine} ApplicationDomain:{appDomain} ProcessId:{processId} ProcessName:{processName} Win32ThreadId:{win32ThreadId} ThreadName:{threadName} ExtendedProperties:{dictionary({key}-{value} )}"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewtype
="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter,Microsoft.Practices.EnterpriseLibrary.Logging,Version=3.1.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overviewname
="TextFormatter"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</formatters>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<categorySources>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addswitchValue="All"name="General">
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<listeners>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addname="FormattedEventLogTraceListener"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</listeners>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</add>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</categorySources>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<specialSources>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<allEventsswitchValue="All"name="AllEvents"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<notProcessedswitchValue="All"name="UnprocessedCategory"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<errorsswitchValue="All"name="LoggingErrors&amp;Warnings">
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<listeners>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
<addname="FormattedEventLogTraceListener"/>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</listeners>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</errors>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</specialSources>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</loggingConfiguration>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
</configuration>
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview


我们现在来运行以下程序:

[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview

从输出的结果可以看出,虽然我们在Main()两次调用了Process方法,但是真正执行的数次只有一次。这是Caching所致,第一次调用PIAB将返回值存入Cache,该Cache EntryKey为参数Order对象。第二次调用由于传入的参数相同,所有直接将上次的结果返回。

上面我看到了Caching的效果,现在我们在看看Logging。默认情况下,Logging entry被写入Event Log。下图就是我们写入的Log
[原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview

· [原创]Enterprise Library Policy Injection Application Block 之一: PIAB Overview
· [原创]Enterprise Library Policy Injection Application Block 之二: PIAB设计和实现原理
· [原创]Enterprise Library Policy Injection Application Block 之三: PIAB的扩展—创建自定义CallHandler(提供Source Code下载)

· [原创]Enterprise Library Policy Injection Application Block 之四:如何控制CallHandler的执行顺序