using KanameFramework.Core.Aop.Attributes;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Security.Permissions;
namespace KanameFramework.Core.Aop {
public class AopRealProxy : RealProxy {
private object aspectInstance;
/// <param name="type">目标类</param>
/// <param name="typeIns">目标类实例</param>
/// <param name="aspectType">切面类</param>
/// <param name="aspectIns">切面类实例</param>
[PermissionSet(SecurityAction.LinkDemand)]
public AopRealProxy(Type type,object typeIns,Type aspectType, object aspectIns) : base(type) {
this.aspectType = aspectType;
this.aspectInstance = aspectIns??Activator.CreateInstance(aspectType);
URI = RemotingServices.Marshal((MarshalByRefObject)(typeIns??Activator.CreateInstance(type))).URI;
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public override IMessage Invoke(IMessage message) {
var properties = message.Properties;
var methodName = (string)properties["__MethodName"];
var argTypes = (Type[])properties["__MethodSignature"];
var args = (object[])properties["__Args"];
var matchAspectMethods = aspectType.GetMethods(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance).Where(m=> {
if (!m.Name.Equals(methodName)) return false;
var attr = m.GetCustomAttribute<AroundAttribute>();
if (attr == null) return false;
return attr.ArgTypes.SequenceEqual(argTypes);
properties["__Uri"] = URI;
if (matchAspectMethods.Count()<1)
return (IMethodReturnMessage)ChannelServices.SyncDispatchMessage(message);
var joinPoint = new JoinPoint(args, () => (IMethodReturnMessage)ChannelServices.SyncDispatchMessage(message));
matchAspectMethods.First().Invoke(aspectInstance, new object[] { joinPoint });
return joinPoint.MethodReturnMessage;
评论