Unity、Exception Handling引入MVP

什么是MVP?在“MVP初探”里就有讲过了,就是一种UI的架构模式。

简单的描述一下Unity和Exception Handling Application Block:

Unity是一个轻量级的可扩展的依赖注入(DI)容器,支持构造函数,属性和方法调用注入。构建一个成功应用程序的关键是实现非常松散的耦合设计。松散耦合的应用程序更灵活,更易于维护 。

微软Enterprise Library EHAB(Exception Handling Application Block)提供了一种基于策略(Policy)的异常处理方式,在不同的环境中,比如多层架构中不同的层次中,我们可以定义不同的异常处理策略。

为使M/V/P之间更好的解耦,我们通过引入Enterprise Library的Exception Handling Application Block来实现异常处理,借助Policy Injection Application Block来实现AOP,即然从2.0开始Unity就有几个内置的Handler(Authorization/Exception Handling/Logging/Performance Counter/Validation),自然也就引入了Unity。

这样,我们就可以做到以AOP的方式处理异常(不仅仅只有异常,还可以是其它的业务无关性处理)。我们通过Unity的使得P对M的依赖得以解除,同时也大大增强了可扩展性和可配置性。将系统的耦合度也除到最低。

实例演练:

这里还是延用《MVP之V和P交互》的例子。

首先,我们来看看Unity如何配置的

  • 修改配置文件添加配置节
<configSections>   ...   <section name="unity"            type=" Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=2.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </configSections>
  • 添加Unity节元素
 <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">   </unity>

这个元素节的名称也就添加配置节时的名称,两者要相同;

  • 添加程序集和命名空间
<assembly name="Handwe.Demo.UnityInMVP" />
    <namespace name="Handwe.Demo.UnityInMVP" />

使得可以在相应的程序集和命名空间里查到相对应的类;在这里也可以添加别名;

  • 添加容器的扩展节
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
    

用于在Unity容器中扩展拦截;

  • 添加默认(未命名)容器container
<container>

</container>

接着,在这个container里注册类型或接口,这里我们注册的是接口,并用于拦载;

  • 注册接口/类型
<register type="ICalculatorView" mapTo="CalculatorView"/>
      <register type="ICalculate" mapTo="Calculate">
        <interceptor type="TransparentProxyInterceptor"/>
        <interceptionBehavior type="PolicyInjectionBehavior"/>
      </register>

注册了两个接口,一个是ICalculatorView并映射到CalculatorView;另外一个是ICalculate映射到Calculate;这里我们只对ICalculate使用了拦截,有三种拦截器,适用于接口或类型,它是接口类型,所以选择透明代理拦截器类型TransparentProxyInterceptor,并使用提供的策略拦载行为PolicyInjectionBehavior.

  • 添加拦截扩展元素
      <extension type="Interception" />
<interception>
        <policy name="policy-exceptionHandler">
          <matchingRule name="auther-rule2" type="MemberNameMatchingRule">
            <constructor>
              <param name="namesToMatch">
                <array type="string[]">
                  <value value="Divide" />
                  <value value="Add" />
                </array>
              </param>
            </constructor>
          </matchingRule>
          <callHandler name="exceptionHandler-handler1" type="Handwe.Demo.UnityInMVP.ExceptionCallHandler, Handwe.Demo.UnityInMVP">
            <constructor>
              <param name="exceptionPolicyName" value="UIExceptionPolicy"/>
              <param name="order" value="1"/>
            </constructor>
          </callHandler>
        </policy>
      </interception>

这里的拦截策略policy-cexeptionHandler我们配置为:使用成员名称配置规则MemberNameMatchingRule,提供的构造函数接受一个名称为nameToMatch,的字符串组string[]的形参,这里提供了两个成员,分别是Divide、Add;而处理程序则是我们通过自定义的,因为我们要把Unity和EHAB集成;这里我们先做下介绍,在ExceptionCallHandler中提供了支持接受两个形参的构造函数,分别是异常处理策略名称exceptionPolicyName和处理程序在管道中的执行顺序order;那么这里的异常处理策略"UIExceptionPolicy"是从哪里来的呢?其实这个就是我们在EHAB中配置的异常处理策略的名称。

有了上面的认识,那么我们现在回过头了看看是如果配置“UIExceptionPloicy”。

 配置EHAB

因为Entlib5不支持使用配置工具来对Unity配置,须要手工配置;EHAB可以用配置工具来配置;我以借助配置工具我们将EHAB的异常处理策略配置为如下:

  • 添加支持的节
<configSections>
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    
  • 具体的配置
  <exceptionHandling>
    <exceptionPolicies>
      <add name="UIExceptionPolicy">
        <exceptionTypes>
          <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="None">
            <exceptionHandlers>
              <add type="Handwe.Demo.UnityInMVP.MessageBoxHandler, Handwe.Demo.UnityInMVP"
                name="Custome Handler" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>

那么,现在很清楚的可以看到我们通过在Unity中配置的拦截处理通过“UIExceptionPolicy”这个名称将它们关联起来。接下来再来看看代码是如何实现的。具体的可以看《Exception Handling引入MVP》这里;

 

代码的实现

主要的一些代码在MVP之V和P交互》的例子中已经实现了,在这里我们来看看新增的两个类:分别是MessageBoxHandler、ExceptionCallHandler;

MessageBoxHandler代码:

  • 引用的程序集

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;

 1 namespace Handwe.Demo.UnityInMVP
 2 {
 3     [ConfigurationElementType(typeof(CustomHandlerData))]
 4     public class MessageBoxHandler : IExceptionHandler
 5     {
 6         public MessageBoxHandler(NameValueCollection igonre)
 7         {
 8 
 9         }
10         public Exception HandleException(Exception exception, Guid handlingInstanceId)
11         {
12             MessageBox.Show(exception.Message, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
13             return exception;
14         }
15     }
1

这个仅仅是在处理异常里弹出一个消息框;

[ConfigurationElementType(typeof(CustomHandlerData))]

注意这行代码的使用,它使得可以在配置文件中配置该处理程序;

public MessageBoxHandler(NameValueCollection igonre)
        {

        }

通过NameValueConllection可以取得在配置文件的的配置;

 

ExceptionCallHandler的实现代码:

 1 namespace Handwe.Demo.UnityInMVP
 2 {
 3     public class ExceptionCallHandler : ICallHandler
 4     {
 5         // Fields
 6         private ExceptionPolicyImpl exceptionPolicy;
 7         private int order;
 8 
 9         public ExceptionCallHandler(string exceptionPolicyName, int order)
10         {
11 
12             this.exceptionPolicy = EnterpriseLibraryContainer.Current.GetInstance<ExceptionPolicyImpl>(exceptionPolicyName);
13             this.order = order;
14         }
15 
16         // Methods
17         public ExceptionCallHandler(ExceptionPolicyImpl exceptionPolicy)
18         {
19             this.exceptionPolicy = exceptionPolicy;
20         }
21 
22         public ExceptionCallHandler(ExceptionPolicyImpl exceptionPolicy, int order)
23             : this(exceptionPolicy)
24         {
25             this.order = order;
26         }
27 
28         public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
29         {
30             if (input == null)
31             {
32                 throw new ArgumentNullException("input");
33             }
34             if (getNext == null)
35             {
36                 throw new ArgumentNullException("getNext");
37             }
38             IMethodReturn return2 = getNext()(input, getNext);
39             if (return2.Exception != null)
40             {
41                 try
42                 {
43                     if (!this.exceptionPolicy.HandleException(return2.Exception))
44                     {
45                         return2.ReturnValue = null;
46                         return2.Exception = null;
47                         if (input.MethodBase.MemberType == MemberTypes.Method)
48                         {
49                             MethodInfo methodBase = (MethodInfo)input.MethodBase;
50                             if (methodBase.ReturnType != typeof(void))
51                             {
52                                 return2.Exception = new InvalidOperationException("CantSwallowNonVoidReturnMessage");
53                             }
54                         }
55                     }
56                 }
57                 catch (Exception exception)
58                 {
59                     return2.Exception = exception;
60                 }
61             }
62             return return2;
63         }
64 
65         // Properties
66         public ExceptionPolicyImpl ExceptionPolicy
67         {
68             get
69             {
70                 return this.exceptionPolicy;
71             }
72         }
73 
74         public int Order
75         {
76             get
77             {
78                 return this.order;
79             }
80             set
81             {
82                 this.order = value;
83             }
84         }
85     }
86 
87 }

ExceptionCallHandler须是ICallHandler的实现,下面这个构造函数重载

public ExceptionCallHandler(string exceptionPolicyName, int order)
        {

            this.exceptionPolicy = EnterpriseLibraryContainer.Current.GetInstance<ExceptionPolicyImpl>(exceptionPolicyName);
            this.order = order;
        }

就是使用到的构造函数数,它有两个形参exceptionPolicyName和order。通过:

this.exceptionPolicy = EnterpriseLibraryContainer.Current.GetInstance<ExceptionPolicyImpl>(exceptionPolicyName);

根据异常处理策略的名称获取所相关异常处理配置;

在调用方法或目标方法后确定是否引发了异常,并通过HandleException检查是否存在异常对象类型由 System.Exception 参数指定匹配策略项,如果有,则调用与该条目关联的处理程序。

if (!this.exceptionPolicy.HandleException(return2.Exception))
                    {
                        return2.ReturnValue = null;
                        return2.Exception = null;
                        if (input.MethodBase.MemberType == MemberTypes.Method)
                        {
                            MethodInfo methodBase = (MethodInfo)input.MethodBase;
                            if (methodBase.ReturnType != typeof(void))
                            {
                                return2.Exception = new InvalidOperationException("CantSwallowNonVoidReturnMessage");
                            }
                        }
                    }

这里是通过被调用的方法是否有无返回值,如果有将方法异常重新引发一个一新的无效操作异常;

小结:

所以通过这样的设计采用Unity作为IoC框架,并且通过Unity的Interception Extension实现AOP,不仅仅是本文提到的Exception Handler。

我们通过Unity的使得P对M的依赖得以解除,同时也大大增强了可扩展性和可配置性。将系统的耦合度也除到最低。

posted @ 2016-07-06 14:12  Ny.z  阅读(755)  评论(0编辑  收藏  举报