RealProxy + ProxyAttribute 実装メモ

using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Activation;

public class WrappingProxy : RealProxy
{
    public WrappingProxy(Type targetType)
        : this(targetType, null)
    {
    }

    public WrappingProxy(Type targetType, MarshalByRefObject targetInstance)
        : base(targetType)
    {
        if (targetInstance != null)
        {
            this.AttachServer(targetInstance);
        }
    }

    public override IMessage Invoke(IMessage msg)
    {
        if (msg is IConstructionCallMessage)
        {
            return this.InitializeServerObject((IConstructionCallMessage)msg);
        }

        IMethodCallMessage methodCallMessage = (IMethodCallMessage)msg;
        MethodBase targetMethod = methodCallMessage.MethodBase;
        object[] args = methodCallMessage.Args;

        ReturnMessage returnMessage;
        try
        {
            object invokeResult = targetMethod.Invoke(this.GetUnwrappedServer(), args);
            returnMessage = new ReturnMessage(invokeResult, args, args.Length, methodCallMessage.LogicalCallContext, methodCallMessage);
        }
        catch (TargetInvocationException ex)
        {
            returnMessage = new ReturnMessage(ex.InnerException, methodCallMessage);
        }
        return returnMessage;
    }
}
using System;

public class WrappingProxyAttribute : ProxyAttribute
{
    public override MarshalByRefObject CreateInstance(Type serverType)
    {
        WrappingProxy proxy = new WrappingProxy(serverType);
        return (MarshalByRefObject)proxy.GetTransparentProxy();
    }
}