[原创]Enterprise Library Policy Injection Application Block 之二: PIAB设计和实现原理

前面一篇文章中,我对Enterprise Library中的PIAB Policy Injection Application Block)作了简单的介绍。在这篇文章主要谈谈我个人对PIAB设计和实现原理的一些理解。在介绍过程中,我尽量采用由浅入深出的方式,同时结合例子、Source Code。希望通过本篇文章让大家对PIAB有一个全面、深刻的认识。

一、MBRObjRefRealProxyTransparentProxy

在真正进入PIAB之前,我们现来谈论一些与之相关的、必要的背景知识。MBRObjRefRealProxyTransparentProxy,对于这些名词,我想熟悉或者接触过.NET Remoting的人肯定不会不陌生。由于PIAB的实现机制依赖于Remoting的这种Marshaling,如果对此不了解的读者将对后面的介绍很难理解,所以很有必要先做以下简单的介绍。

我们知道,CLR通过AppDomain实现不同Application之间的隔离,在通常情况下,不同AppDomain不同共享内存。在一个AppDomain中创建的对象不能直接被运行在另一个AppDomain的程序使用。跨AppDomain对象的共享依赖于一个重要的过程:Marshaling。我们有两种不同的Marshaling方式:Marshaling by ValueMarshaling by Reference。前者采用的是Serialization/Deserialization的方式,而后者则是采用传递Reference的方式来实现,其实现原来如下:

Remoting Infrastructure先生成对象的ObjRef InstanceObjRefSystem.Runtime.Remoting.ObjRef)代表远程对象的一个Reference,存储着跨AppDomain远程调用所需的所有的信息,比如URI、类型的层次结构、以及实现的Interface等等。ObjRef是可以序列化的,也就是说它可以按照by Value的方式进行Marshaling。所以可以这么说Marshaling by Reference依赖对对ObjRefMarshaling by Value

ObjRef产地到另一个AppDomain的实现,将根据ObjRef的数据生成两个Proxy对象:RealProxyTransparentProxyRealProxy根据ObjRef创建,通过RealProxy创建TransparentProxy。当进行远程调用的时候,Client直接和TransparentProxy打交道,对TransparentProxy的调用将会ForwardRealProxyRealProxy通过Remoting InfrastructureCommunicateActivation机制将Invocate传递给被激活的Remote Object

MBR通常在一个跨AppDomain的环境下实现远程调用,但是这种机制在用一个AppDomian依然有效,而且可以免去跨AppDomain的性能损失。PIAB就是充分运用了这种在同一个AppDomain下的MBR

二、Method Interception & Custom RealProxy

在第一部分我们知道,PIAB的实现是通过将Policy应用到对应的Method上,在真正执行目标对象具体的方法的之前,PIAB将整个方法的调用拦截,然后逐个调用应在Method上的Policy包含的所有CallHandler(在前一章我们说过Policy = Matching Rule + Call Handler),最后再调用真正目标对象的方法。我们把这种机制成为Method Injection

如何才有实现这样的Method Injection呢?这就要需要使用到我们在上面一节介绍的MBR了。通过上面的介绍,我们知道我们调用一个MBR Object的过程是这样的:

Client Code==〉Transparent Proxy==〉Real Proxy==〉Target Object

在上面的Invocate Chain中,由于真正的目标对象的方法在最后一部才被调用,我们完全有可以在中途将调用劫持,使之先调用我们的CallHandler。而这种Inject的突破口在于RealProxy。在FCLFramework Class Library)中RealProxySystem.Runtime.Remoting.Proxies.RealProxy)是个特殊的Abstract Class,你可以继承RealProxy定义你自己的Custom RealProxy,将你需要注入的操作写在Invoke方法中。PIAB采用的就是这样一种解决方案。

我们先不忙介绍PIAB的具体的实现原理,因为相对比较复杂。为了使读者能够更加容易地理解PIAB的实现,我写了一个简单的例子。我们它能够大体体现PIAB的实现机制。

这是一个简单的Console Application,我首先定义了一个Custom RealProxy

   public class MyRealProxy<T>:RealProxy

    {

       private T _target;

       public MyRealProxy(T target)

           : base(typeof(T))

       {

           this._target = target;

       }

      

        public override IMessage Invoke(IMessage msg)

        {

            //Invoke injected pre-operation.

            Console.WriteLine("The injected pre-operation is invoked");

            //Invoke the real target instance.

            IMethodCallMessage callMessage = (IMethodCallMessage)msg;

            object returnValue = callMessage.MethodBase.Invoke(this._target, callMessage.Args);

            //Invoke the injected post-operation.

            Console.WriteLine("The injected post-peration is executed");

            //Return

            return new ReturnMessage(returnValue, new object[0], 0, null, callMessage);

        }
    }

这是一个GenericRealProxy。在Invoke方法中,两个Console.Write()代表PIAB注入的CallHandler的调用(对于CallHandler的操作可以是在调用Target Object之前调用,也可以在之后调用,我们不妨称这两种类型的操作为Pre-operationPost-op

eration)。而对Target object的调用实际上是通过Reflection的方式调用的(callMessage.MethodBase.Invoke)。MyRealProxy通过传入Target Instance来创建。

我们在创建一个Factory Class,用于创建TransparentProxy。在PIAB中,这样一个ClassMicrosoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjection来充当。

public static class PolicyInjectionFactory

{

        public static T Create<T>()

        {

            T instance = Activator.CreateInstance<T>();

            MyRealProxy<T> realProxy = new MyRealProxy<T>(instance);

            T transparentProxy = (T)realProxy.GetTransparentProxy();

            return transparentProxy;

        }
}

先通过Reflection的方式来创建Target Instance。通过该Instance创建我们在上面定义的Custom RealProxy。最后通过RealProxy返回一个TransparentProxy

有了上面两个Class,我们的编写如下的Code来验证我们自己的Method Injection

public class Foo:MarshalByRefObject

{

        public void DoSomeThing()

        {

            Console.WriteLine("The method of target object is invoked!");

        }
}

public class Program

{

        public static void Main()

        {

            Foo foo = PolicyInjectionFactory.Create<Foo>();

            foo.DoSomeThing();

        }
}

我们来看看程序运行后的结果:


可以看到正式我们需要的结果。从这个例子中我们可以看到,我们的
Client code中包含的仅仅是Business Logic相关的code, 而另外一些业务无关的Code则是通过Custom RealProxy的形式注入到Invocation Stack中。这充分体现了Business ConcernCrosscutting Concern的分离。

三、Call Handler Pipeline

我想有了上面的理论和例子作基础,大家对于PIAB真正的实现不难理解了。我们先来介绍一下PI一个重要的概念:CallHandler Pipeline。我们知道Policy被运用Method方面,一个Policy有多个CallHandler。所有一个Method往往关联着一连串的CallHandler。这种现在很常见,就上我们第一部分给出的例子一样,一个简单的ProcessOrder方面需要执行许多额外的业务无关的逻辑:AuthorizationAuditingTransaction EnlistException HandlingLogging

PIAB中,这些基于某个Method的所有CallHandler逐个串联在一起,组成一个CallHandler Pipeline 。具体情况如下图:


我们从
Class Diagram的角度来认识CallHandler Pipeline (在PIAB中通过Microsoft.Practices.EnterpriseLibrary.PolicyInjection.HandlerPipeline来表示)。



public delegate IMethodReturnInvokeHandlerDelegate(IMethodInvocation input, GetNextHandlerDelegate getNext);

public interface IMethodInvocation

{

    // Methods

    IMethodReturnCreateExceptionMethodReturn(Exception ex);

    IMethodReturnCreateMethodReturn(object returnValue, params object[] outputs);

    // Properties

    IParameterCollectionArguments { get; }

    IParameterCollectionInputs { get; }

    IDictionaryInvocationContext { get; }

    MethodBaseMethodBase { get; }

    objectTarget { get; }
}
public delegate InvokeHandlerDelegate GetNextHandlerDelegate();
 

public interface ICallHandler

{

    // Methods

    IMethodReturnInvoke(IMethodInvocation input, GetNextHandlerDelegate getNext);
}

IMethodInvocation代表对一个方法的调用,它封装了一个Method Invocation的相关信息。比如:Parameter ListInvocation ContextTarget Object. InvokeHandlerDelegate代表的是对CallHandler的调用,由于所有的CallHandler被串成一个CallHandler Pipeline ,在调用了当前CallHandler之后,需要调用Pipeline中后一个CallHandler,对后一个CallHandler调用通过一个DelegateGetNextHandlerDelegate来表示,而该Delegate的返回值是InvokeHandlerDelegate。结合上面的CallHandler Pipeline 的链状结构,对这些应该不难理解。

我们最后来看看HandlerPipeline的定义,它的所有的CallHandler通过一个List来表示。

public class HandlerPipeline

{

    // Fields

    private List<ICallHandler> handlers;

    // Methods

    public HandlerPipeline();

    public HandlerPipeline(IEnumerable<ICallHandler> handlers);

    public IMethodReturnInvoke(IMethodInvocation input, InvokeHandlerDelegate target);
 }

HandlerPipeline通过Invoke开始对其CallHandler PipeLine的调用:

public IMethodReturn Invoke(IMethodInvocation input, InvokeHandlerDelegate target)

{

    if (this.handlers.Count == 0)

    {

        return target(input, null);

    }

    int handlerIndex = 0;

    return this.handlers[0].Invoke(input, delegate {

        handlerIndex++;

        if (handlerIndex < this.handlers.Count)

        {

            ICallHandler local1 = this.handlers[handlerIndex];

            return new InvokeHandlerDelegate(local1.Invoke);

        }

        return target;

    });

}

逻辑并不复杂,按照CallHandler List的先后顺序逐个调用,最后调用Target Object。方法中的第二个参数代表target代表对Target Object的调用。

四、PIAB中的Custom RealProxyInterceptingRealProxy

我们一直再强调,PIAB实际上是通过自定义RealProxy来实现的。而且在第二节我们也实验了这种做法的可行性。我们现在就来看看PIABCustom RealProxyMicrosoft.Practices.EnterpriseLibrary.PolicyInjection.RemotingInterception.InterceptingRealProxy

public class InterceptingRealProxy : RealProxy, IRemotingTypeInfo
{

    // Fields

    private Dictionary<MethodBase, HandlerPipeline> memberHandlers;

    private readonly object target;

    private string typeName;

    // Methods   

    public
InterceptingRealProxy(object target, Type classToProxy, PolicySet policies);

    private void AddHandlersForInterface(Type targetType, Type itf);

    private void AddHandlersForType(Type classToProxy, PolicySet policies);

    public bool CanCastTo(Type fromType, object o);

    public override IMessage Invoke(IMessage msg);

    // Properties

    public object Target { get; }

    public string TypeName { get; set; }

}

上面是它所有的成员定义,其中memberHandlers是一个以MethodBaseKeyDictionary,表示应用在Target Object上面的所有的CallHandler Pipeline。通过这个很容易获得某个具体的方法调用的Pipeline。而target值得是真正的Target Object

我们着重来看看Invoke的定义:

public override IMessage Invoke(IMessage msg)

{

    HandlerPipeline pipeline;

    IMethodCallMessage callMessage = (IMethodCallMessage) msg;

    if (this.memberHandlers.ContainsKey(callMessage.MethodBase))

    {

        pipeline = this.memberHandlers[callMessage.MethodBase];

    }

    else

    {

        pipeline = new HandlerPipeline();

    }

    RemotingMethodInvocation invocation = new RemotingMethodInvocation(callMessage, this.target);

    return ((RemotingMethodReturn) pipeline.Invoke(invocation, delegate (IMethodInvocation input, GetNextHandlerDelegate getNext) {

        try

        {

            object returnValue = callMessage.MethodBase.Invoke(this.target, invocation.Arguments);

            return input.CreateMethodReturn(returnValue, invocation.Arguments);

        }

        catch (TargetInvocationException exception)

        {

            return input.CreateExceptionMethodReturn(exception.InnerException);

        }

    })).ToMethodReturnMessage();

}

上面的一段代码不长,多看几遍应该不难理解。总的来说上面的Code现根据msg解析出MethodBase,再获取对应的CallHandler Pipeline,最后调用Pipeline

五、Policy Injection Transparent Proxy Factory

介绍到这里,细心的读者可以意识到了,我们实际上还还有两件事情没有解决:CallHandler Pipeline的初始化和Transparent Proxy的创建。这两件事情都由PolicyInject.Create和方法来完成。

需要指出的,应用PIABClass需要具有两个条件中至少一个:

·         Class继承System.MarshalByRefObject

·         Class实现某个Interface

PolicyInjectiond提供了两种类型的Create方式,一种需要制定Interface,另一种不需要:

public static TInterface Create<TObject, TInterface>(params object[] args);

public static TObject Create<TObject>(params object[] args);

其实还有两个重载,在这里就不需要多做介绍了。在具体的实现中,最终又是调用一个PolicyInjector对象来实现的。

public static TObject Create<TObject>(params object[] args)

{

    return DefaultPolicyInjector.Create<TObject>(args);
 }

public static TInterface Create<TObject, TInterface>(params object[] args)

{

returnDefaultPolicyInjector.Create<TObject, TInterface>(args);
 }

PolicyInjector是一个Abstract Class。其中Policies属性代表应用在该对象上的所有PolicyPolicy = CallHandler + Matching Rule

[CustomFactory(typeof(PolicyInjectorCustomFactory))]

public abstract class PolicyInjector

{

    // Fields

    private PolicySetpolicies;

    // Methods

    public PolicyInjector();

    public PolicyInjector(PolicySet policies);

    public TInterface Create<TObject, TInterface>(params object[] args);

    public TObject Create<TObject>(params object[] args);

    public objectCreate(Type typeToCreate, params object[] args);

publicobjectCreate(Type typeToCreate, Type typeToReturn, params object[] args);

… … … … …

    // Properties

    public PolicySetPolicies { get; set; }
}

PolicyInjection Class中定义了一个叫做DefaultPolicyInjector的属性,其定义如下:

private static PolicyInjectorDefaultPolicyInjector

{

    get

    {

        if (defaultPolicyInjector == null)

        {

            lock (singletonLock)

            {

                if (defaultPolicyInjector == null)

                {

                    defaultPolicyInjector = GetInjectorFromConfig(ConfigurationSourceFactory.Create());

                }

            }

        }

        return defaultPolicyInjector;

    }
}

由于上面这个方法具体调用的Stack trace太深了,不可能很详细地指出其具体的实现。简单地说,该属性会返回一个默认的PolicyInjectorRemotingPolicyInjector并对其进行初始化。初始化的内容就包括初始化所有的Policy(这就是我们在本节开始提出的CallHandler Pipeline的初始化)。由于我们可以有两种方式将Policy映射到目标成员:AttributeConfiguration。所有具体的做法是先通过分析Configuration找出所有通过configuration方式添加的Policy,然后通过Reflection找出所有通过使用Attribute方式添加的Policy。所以,如果你通过两种方式将相同的Policy应用到同一个对象上,该对象上将会有两个一样CallHandler,个人觉得这是一个值得商榷的做法,我不太赞成这样的行为。

我们接着看PolicyInjector接着是如何工作的:

public TInterface Create<TObject, TInterface>(params object[] args)

{

    return (TInterface) this.Create(typeof(TObject), typeof(TInterface), args);
}

public TObject Create<TObject>(params object[] args)

{

    return (TObject) this.Create(typeof(TObject), typeof(TObject), args);
}

上面连个方法由于调用到同一个Create Overload

publicobjectCreate(Type typeToCreate, Type typeToReturn, params object[] args)

{

    PolicySet policiesFor = this.policies.GetPoliciesFor(typeToCreate);

    this.EnsureTypeIsInterceptable(typeToReturn, policiesFor);

    return this.DoCreate(typeToCreate, typeToReturn, policiesFor, args);
 }

首先找出对应TypePolicy,然后判断该类型是否支持Method InterceptionRemotingPolicyInjector对该方法是这样实现的:要么继承MarshalByRefObjectClass,要么是个Interface。所以我们才有本节开始提出的两个条件。

public override boolTypeSupportsInterception(Type t)

{

    if (!typeof(MarshalByRefObject).IsAssignableFrom(t))

    {

        return t.IsInterface;

    }

    return true;
}

上面连个方法由于调用到同一个Create Overload

publicobjectCreate(Type typeToCreate, Type typeToReturn, params object[] args)

{

    PolicySet policiesFor = this.policies.GetPoliciesFor(typeToCreate);

    this.EnsureTypeIsInterceptable(typeToReturn, policiesFor);

    return this.DoCreate(typeToCreate, typeToReturn, policiesFor, args);
 }

首先找出对应TypePolicy,然后判断该类型是否支持Method InterceptionRemotingPolicyInjector对该方法是这样实现的:要么继承MarshalByRefObjectClass,要么是个Interface。所以我们才有本节开始提出的两个条件。

protected override object DoWrap(object instance, Type typeToReturn, PolicySet policiesForThisType)

{

    if (PolicyInjector.PolicyRequiresInterception(policiesForThisType))

    {

        InterceptingRealProxy proxy = new InterceptingRealProxy(this.UnwrapTarget(instance), typeToReturn, policiesForThisType);

        return proxy.GetTransparentProxy();

    }

    return instance;

}

和我们给出的例子差不多,创建RealPoxy,根据该RealProxy返回Transparent Proxy

五、Policy Injection Design

最后给出整个PIAB实现的所使用的Class,基本上所有的Class都在上面的内容中介绍过了:


在本系列的第三部分,我将介绍如何创建
Custom Handler,以及如何将他采用不同的方式应用到你的Application中。

· [原创]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的执行顺序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值