深度剖析 PIAB 內部實現:.NET Remoting MBR 架構、自訂 RealProxy 方法攔截、CallHandler Pipeline 串聯執行、PolicyInjector 工廠建構 Transparent Proxy 全流程。
ObjRef (含 URI、型別階層、介面等)ObjRef 建立,處理真正呼叫邏輯 (可繼承自訂)呼叫鏈:Client → TransparentProxy → RealProxy.Invoke() → Target。在 RealProxy.Invoke 中插入 Pre/Post 作業即實現 AOP。
public class MyRealProxy<T> : RealProxy
{
private T _target;
public MyRealProxy(T target) : base(typeof(T)) { _target = target; }
public override IMessage Invoke(IMessage msg)
{
Console.WriteLine("Pre-operation injected");
var callMsg = (IMethodCallMessage)msg;
var ret = callMsg.MethodBase.Invoke(_target, callMsg.Args);
Console.WriteLine("Post-operation injected");
return new ReturnMessage(ret, null, 0, null, callMsg);
}
}
public static class PolicyInjectionFactory
{
public static T Create<T>()
{
var inst = Activator.CreateInstance<T>();
var rp = new MyRealProxy<T>(inst);
return (T)rp.GetTransparentProxy();
}
}

驗證:Business Logic 僅一行,Crosscutting Concern 由 Proxy 注入,完美分離。
一個方法常需多個 Handler:Authorization → Auditing → Transaction → Exception Handling → Logging。
PIAB 將同一方法的所有 Handler 串成 HandlerPipeline:

public delegate IMethodReturn InvokeHandlerDelegate(IMethodInvocation input, GetNextHandlerDelegate getNext);
public delegate InvokeHandlerDelegate GetNextHandlerDelegate();
public interface IMethodInvocation
{
IParameterCollection Arguments { get; }
IParameterCollection Inputs { get; }
IDictionary InvocationContext { get; }
MethodBase MethodBase { get; }
object Target { get; }
IMethodReturn CreateExceptionMethodReturn(Exception ex);
IMethodReturn CreateMethodReturn(object returnValue, params object[] outputs);
}
public interface ICallHandler
{
IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext);
}
public class HandlerPipeline
{
private List<ICallHandler> handlers;
public IMethodReturn Invoke(IMethodInvocation input, InvokeHandlerDelegate target)
{
if (handlers.Count == 0) return target(input, null);
int idx = 0;
return handlers[0].Invoke(input, delegate {
idx++;
return idx < handlers.Count
? new InvokeHandlerDelegate(handlers[idx].Invoke)
: target;
});
}
}
遞迴委派鏈:每個 Handler 執行完呼叫 getNext 執行下一個,最後執行 target (目標方法)。
public class InterceptingRealProxy : RealProxy, IRemotingTypeInfo
{
private Dictionary<MethodBase, HandlerPipeline> memberHandlers;
private readonly object target;
public override IMessage Invoke(IMessage msg)
{
var callMsg = (IMethodCallMessage)msg;
var pipeline = memberHandlers.ContainsKey(callMsg.MethodBase)
? memberHandlers[callMsg.MethodBase]
: new HandlerPipeline();
var invocation = new RemotingMethodInvocation(callMsg, target);
return ((RemotingMethodReturn) pipeline.Invoke(invocation, delegate {
try {
var ret = callMsg.MethodBase.Invoke(target, invocation.Arguments);
return invocation.CreateMethodReturn(ret, invocation.Arguments);
} catch (TargetInvocationException ex) {
return invocation.CreateExceptionMethodReturn(ex.InnerException);
}
})).ToMethodReturnMessage();
}
}
memberHandlers:方法 → Pipeline 字典,初始化時建構MethodBase 取得對應 Pipeline 執行public abstract class PolicyInjector
{
public PolicySet Policies { get; set; }
public TObject Create<TObject>(params object[] args) => (TObject)Create(typeof(TObject), typeof(TObject), args);
public TInterface Create<TObject, TInterface>(params object[] args) => (TInterface)Create(typeof(TObject), typeof(TInterface), args);
public object Create(Type typeToCreate, Type typeToReturn, params object[] args)
{
var policiesFor = Policies.GetPoliciesFor(typeToCreate);
EnsureTypeIsInterceptable(typeToReturn, policiesFor);
return DoCreate(typeToCreate, typeToReturn, policiesFor, args);
}
protected override object DoWrap(object instance, Type typeToReturn, PolicySet policiesForThisType)
{
if (PolicyInjector.PolicyRequiresInterception(policiesForThisType))
{
var proxy = new InterceptingRealProxy(UnwrapTarget(instance), typeToReturn, policiesForThisType);
return proxy.GetTransparentProxy();
}
return instance;
}
}
public override bool TypeSupportsInterception(Type t)
=> typeof(MarshalByRefObject).IsAssignableFrom(t) || t.IsInterface;
故目標類別必須繼承 MarshalByRefObject 或實作介面。



下一篇將介紹自訂 CallHandler 開發實戰。