软件工程中的大多数思想都是集中在管理复杂度上面的--
结构化编程尝试通过粗粒度的代码与设计划分来降低复杂度;
面向对象编程尝试通过建立结合状态与行为的抽象体来降低复杂度;
基于组件的软件尝试通过基于抽象接口和协议划分应用程序模块来降低复杂度。
基于组件的软件的梦想是构造一个世界,让水平一般的程序员就能使用高级语言和工具将组件组装起来。这当然假设这个世界里面的问题域能被分解成相互之间通过简单的方法调用进行交互的各种离散组件。
基于组件的软件的前提却忽略了这样一个事实,一个程序的特定方面倾向于分散到一个应用的多个部分。安全性就是这样的一个方面,线程管理也是,并发控制也是,这个列表会很长。
不可避免地,一个应用趋于被众多处理那些不是问题域中心的程序方面的代码片断污染。通常,这些方面又倾向于跨问题域,因此需要可复用的解决方案。致力提供机制来解决这类问题的就是AOP(面向方面编程),一个在1997年先后被Gregor Kiczales,和Xeros PARC 提出来的术语。
CLR的AOP机制基本上就是将方法调用看作消息交换。
下面用代码说明这个机制:
using System;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Services;
using System.Runtime.Remoting.Contexts;
using System.Threading;
using System.Diagnostics;
![](/Images/OutliningIndicators/None.gif)
namespace MsgAsMethodCalls
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
public interface ICaculator
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
double Add(double x, double y);
double Multiply(double x, double y);
}
![](/Images/OutliningIndicators/InBlock.gif)
public class MyProxy : RealProxy
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public MyProxy() : base(typeof(ICaculator))
{ }
![](/Images/OutliningIndicators/InBlock.gif)
public override IMessage Invoke(IMessage msg)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
if (msg as IMethodCallMessage != null)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
IMessage response = Program.ProcessMessage(msg as IMethodCallMessage);
return response;
}
return null;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class PriorityProxy : RealProxy
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
readonly MarshalByRefObject target;
readonly ThreadPriority level;
![](/Images/OutliningIndicators/InBlock.gif)
public PriorityProxy(MarshalByRefObject target,
Type type,
ThreadPriority level)
: base(type)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.target = target;
this.level = level;
}
![](/Images/OutliningIndicators/InBlock.gif)
public override IMessage Invoke(IMessage request)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
IMethodCallMessage call = (IMethodCallMessage)request;
![](/Images/OutliningIndicators/InBlock.gif)
Program.WireTap(call);
![](/Images/OutliningIndicators/InBlock.gif)
// step 1: adjust priority
Thread here = Thread.CurrentThread;
ThreadPriority old = here.Priority;
here.Priority = level;
// step 2: forward call
IMessage response = null;
![](/Images/OutliningIndicators/InBlock.gif)
IConstructionCallMessage ctor = call as IConstructionCallMessage;
![](/Images/OutliningIndicators/InBlock.gif)
if (ctor != null)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// we are holding a TP, so grab its RP
RealProxy defaultProxy = RemotingServices.GetRealProxy(target);
// as intermediatoe RP to invoke constructor
defaultProxy.InitializeServerObject(ctor);
// get OUR TP
MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy();
// return a message containing our TP as the result of the constuctor call
response = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp);
}
else
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
response = RemotingServices.ExecuteMessage(target, call);
}
![](/Images/OutliningIndicators/InBlock.gif)
// step 3: restore old priority
here.Priority = old;
// step 4: return response message to TP
return response;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
[AttributeUsage(AttributeTargets.Class)]
public class PriorityProxyAttribute : ProxyAttribute
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
ThreadPriority level;
public PriorityProxyAttribute(ThreadPriority level)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.level = level;
}
![](/Images/OutliningIndicators/InBlock.gif)
public override MarshalByRefObject CreateInstance(Type t)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// note that we delegate to our base to get an
// uninitialized instance!
MarshalByRefObject target = base.CreateInstance(t);
PriorityProxy rp = new PriorityProxy(target, t, level);
return (MarshalByRefObject)rp.GetTransparentProxy();
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class PriorityProperty : IContextProperty
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
ThreadPriority level;
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public ThreadPriority Level
{ get
{ return level; } }
internal PriorityProperty(ThreadPriority level)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{ this.level = level; }
![](/Images/OutliningIndicators/InBlock.gif)
// IContextProperty members
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public string Name
{ get
{ return "ThreadPriority"; } }
public bool IsNewContextOK(Context ctx)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return true;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void Freeze(Context ctx)
{ }
}
![](/Images/OutliningIndicators/InBlock.gif)
public class PriorityAttribute : Attribute, IContextAttribute
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
ThreadPriority level;
internal PriorityAttribute(ThreadPriority level)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{ this.level = level; }
![](/Images/OutliningIndicators/InBlock.gif)
// IContextAttribute members
public bool IsContextOK(Context current,
IConstructionCallMessage ctor)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Our property must be present!
object prop = current.GetProperty("ThreadPriority");
if (prop == null) return false;
// and its level must match the attribute's
PriorityProperty pp = (PriorityProperty)prop;
return pp.Level == this.level;
}
![](/Images/OutliningIndicators/InBlock.gif)
public void GetPropertiesForNewContext(
IConstructionCallMessage ctor)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// create new properties
IContextProperty prop = new PriorityProperty(this.level);
// associate property with constructor call
ctor.ContextProperties.Add(prop);
![](/Images/OutliningIndicators/InBlock.gif)
ctor.ContextProperties.Add(new TimingProperty());
![](/Images/OutliningIndicators/InBlock.gif)
ctor.ContextProperties.Add(new BoostProperty());
![](/Images/OutliningIndicators/InBlock.gif)
ctor.LogicalCallContext.SetData("clientpriority", new EnvoyData(Thread.CurrentThread.Priority));
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public abstract class DefaultSink : IMessageSink
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
readonly protected IMessageSink next;
public DefaultSink(IMessageSink next)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.next = next;
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public IMessageSink NextSink
{ get
{ return next; } }
![](/Images/OutliningIndicators/InBlock.gif)
public virtual IMessage SyncProcessMessage(IMessage request)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
IMessage response = next.SyncProcessMessage(request);
return response;
}
![](/Images/OutliningIndicators/InBlock.gif)
public virtual IMessageCtrl AsyncProcessMessage(IMessage request,
IMessageSink upcall)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
IMessageCtrl ctrl = next.AsyncProcessMessage(request, upcall);
return ctrl;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class ServerTimingSink : DefaultSink
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
public ServerTimingSink(IMessageSink next)
: base(next)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{ }
![](/Images/OutliningIndicators/InBlock.gif)
[ContextStatic]
static internal long totalTicks = 0;
![](/Images/OutliningIndicators/InBlock.gif)
public override IMessage SyncProcessMessage(IMessage r)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
long start = DateTime.Now.Ticks;
IMessage p = next.SyncProcessMessage(r);
long end = DateTime.Now.Ticks;
totalTicks += end - start;
return p;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class ClientTimingSink : DefaultSink
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
public ClientTimingSink(IMessageSink next)
: base(next)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{ }
![](/Images/OutliningIndicators/InBlock.gif)
public override IMessage SyncProcessMessage(IMessage r)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
long start = DateTime.Now.Ticks;
IMessage p = next.SyncProcessMessage(r);
long end = DateTime.Now.Ticks;
ServerTimingSink.totalTicks += end - start;
return p;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class TimingProperty
: IContextProperty,
IContributeClientContextSink,
IContributeServerContextSink
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
IContributeClientContextSink Members#region IContributeClientContextSink Members
![](/Images/OutliningIndicators/InBlock.gif)
public IMessageSink GetClientContextSink(IMessageSink nextSink)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return new ClientTimingSink(nextSink);
}
![](/Images/OutliningIndicators/InBlock.gif)
#endregion
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
IContributeServerContextSink Members#region IContributeServerContextSink Members
![](/Images/OutliningIndicators/InBlock.gif)
public IMessageSink GetServerContextSink(IMessageSink nextSink)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return new ServerTimingSink(nextSink);
}
![](/Images/OutliningIndicators/InBlock.gif)
#endregion
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
IContextProperty Members#region IContextProperty Members
![](/Images/OutliningIndicators/InBlock.gif)
public void Freeze(Context newContext)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/InBlock.gif)
}
![](/Images/OutliningIndicators/InBlock.gif)
public bool IsNewContextOK(Context newCtx)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return true;
}
![](/Images/OutliningIndicators/InBlock.gif)
public string Name
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return "TimingProperty"; }
}
![](/Images/OutliningIndicators/InBlock.gif)
#endregion
}
![](/Images/OutliningIndicators/InBlock.gif)
internal class EnvoyData : ILogicalThreadAffinative
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
internal ThreadPriority clientPriority;
internal EnvoyData(ThreadPriority level)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.clientPriority = level;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class PriorityEnvoySink : DefaultSink
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public PriorityEnvoySink(IMessageSink next) : base(next)
{ }
![](/Images/OutliningIndicators/InBlock.gif)
public override IMessage SyncProcessMessage(IMessage request)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
IMethodCallMessage call = (IMethodCallMessage)request;
ThreadPriority p = Thread.CurrentThread.Priority;
EnvoyData ed = new EnvoyData(p);
call.LogicalCallContext.SetData("clientpriority", ed);
return next.SyncProcessMessage(call);
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class PriorityServerSink : DefaultSink
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public PriorityServerSink(IMessageSink next) : base(next)
{ }
![](/Images/OutliningIndicators/InBlock.gif)
public override IMessage SyncProcessMessage(IMessage request)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// grab caller's priority from call context
IMethodCallMessage call = (IMethodCallMessage)request;
LogicalCallContext cc = call.LogicalCallContext;
EnvoyData ed = (EnvoyData)cc.GetData("clientpriority");
cc.FreeNamedDataSlot("clientpriority");
// proceed to boost-dispatch-unboost
Thread here = Thread.CurrentThread;
ThreadPriority old = here.Priority;
if (ed.clientPriority != ThreadPriority.Highest)
here.Priority = ed.clientPriority + 1;
IMessage resp = next.SyncProcessMessage(call);
if (ed.clientPriority != ThreadPriority.Highest)
here.Priority = old;
return resp;
}
}
![](/Images/OutliningIndicators/InBlock.gif)
public class BoostProperty :
IContextProperty,
IContributeServerContextSink,
IContributeEnvoySink
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
IContextProperty Members#region IContextProperty Members
![](/Images/OutliningIndicators/InBlock.gif)
public void Freeze(Context newContext)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
}
![](/Images/OutliningIndicators/InBlock.gif)
public bool IsNewContextOK(Context newCtx)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return true;
}
![](/Images/OutliningIndicators/InBlock.gif)
public string Name
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{ return "Boost"; }
}
![](/Images/OutliningIndicators/InBlock.gif)
#endregion
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
IContributeServerContextSink Members#region IContributeServerContextSink Members
![](/Images/OutliningIndicators/InBlock.gif)
public IMessageSink GetServerContextSink(IMessageSink nextSink)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return new PriorityServerSink(nextSink);
}
![](/Images/OutliningIndicators/InBlock.gif)
#endregion
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
IContributeEnvoySink Members#region IContributeEnvoySink Members
![](/Images/OutliningIndicators/InBlock.gif)
public IMessageSink GetEnvoySink(MarshalByRefObject obj, IMessageSink nextSink)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return new PriorityEnvoySink(nextSink);
}
![](/Images/OutliningIndicators/InBlock.gif)
#endregion
}
![](/Images/OutliningIndicators/InBlock.gif)
public class MyCalc : ContextBoundObject, ICaculator
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
public static MyCalc Create(ThreadPriority level)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
MyCalc target = new MyCalc();
PriorityProxy rp = new PriorityProxy(target, typeof(MyCalc), level);
return (MyCalc)rp.GetTransparentProxy();
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
private MyCalc()
{ }
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public double Add(double x, double y)
{ return x + y; }
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public double Multiply(double x, double y)
{ return x * y; }
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
[PriorityProxy(ThreadPriority.Highest)]
public class MyCalc3 : ContextBoundObject, ICaculator
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public double Add(double x, double y)
{
Console.WriteLine(Thread.CurrentThread.Priority);
return x + y;
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public double Multiply(double x, double y)
{ return x * y; }
}
![](/Images/OutliningIndicators/InBlock.gif)
[Priority(ThreadPriority.Highest)]
public class MyCalc5 : ContextBoundObject, ICaculator
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public double Add(double x, double y)
{
// grab the object's context
Context here = Thread.CurrentContext;
// fecth the priority property
IContextProperty p = here.GetProperty("ThreadPriority");
PriorityProperty pp = (PriorityProperty)p;
Debug.Assert(pp.Level == ThreadPriority.Highest);
![](/Images/OutliningIndicators/InBlock.gif)
Console.WriteLine(Thread.CurrentThread.Priority);
![](/Images/OutliningIndicators/InBlock.gif)
return x + y;
}
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public double Multiply(double x, double y)
{ return x * y; }
}
![](/Images/OutliningIndicators/InBlock.gif)
class Program
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public static void WireTap(IMethodMessage msg)
{
IMethodCallMessage call = (IMethodCallMessage)msg;
Console.WriteLine("<{0}>",call.MethodName);
for(int i=0;i<call.ArgCount;++i)
Console.WriteLine("<{0}>{1}</{0}>",
call.GetArgName(i),
call.GetArg(i));
![](/Images/OutliningIndicators/InBlock.gif)
Console.WriteLine("</{0}>",call.MethodName);
}
![](/Images/OutliningIndicators/InBlock.gif)
public static IMethodReturnMessage ProcessMessage(IMethodCallMessage request)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
switch (request.MethodName)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
case "Add":
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
double x = (double)request.GetInArg(0);
double y = (double)request.GetInArg(1);
double result = x + y;
return new ReturnMessage(result, null, 0, null, request);
}
case "Multiply":
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
double x = (double)request.GetInArg(0);
double y = (double)request.GetInArg(1);
double result = x * y;
return new ReturnMessage(result, null, 0, null, request);
}
default:
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string exm = string.Format("{0} not implemented",
request.MethodName);
Exception ex = new NotImplementedException(exm);
return new ReturnMessage(ex, request);
}
}
}
![](/Images/OutliningIndicators/InBlock.gif)
static void Main(string[] args)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// isinst
MyProxy rp = new MyProxy();
object tp = rp.GetTransparentProxy();
ICaculator calc = tp as ICaculator;
![](/Images/OutliningIndicators/InBlock.gif)
Debug.Assert(calc != null);
![](/Images/OutliningIndicators/InBlock.gif)
double result = calc.Add(3, 4);
![](/Images/OutliningIndicators/InBlock.gif)
Debug.Assert(result == 7);
![](/Images/OutliningIndicators/InBlock.gif)
// factory method
calc = MyCalc.Create(ThreadPriority.Highest);
result = calc.Add(3, 4);
![](/Images/OutliningIndicators/InBlock.gif)
Debug.Assert(result == 7);
![](/Images/OutliningIndicators/InBlock.gif)
// ProxyAttribute
calc = new MyCalc3();
result = calc.Add(3, 4);
![](/Images/OutliningIndicators/InBlock.gif)
Debug.Assert( result == 7);
![](/Images/OutliningIndicators/InBlock.gif)
// ContextProperty
calc = new MyCalc5();
result = calc.Add(3, 4);
![](/Images/OutliningIndicators/InBlock.gif)
Debug.Assert(result == 7);
}
}
}
![](/Images/OutliningIndicators/None.gif)