抄来的AOP的程序,C#实现的

namespace LiangQ.UserAttribute
{
[System.AttributeUsage(AttributeTargets.All)]
public class AuthAttribute : ContextAttribute//contextattribute是所有上下文属性的根。
{
public string ObjectName;

//public AuthAttribute() : base("Auth") { }

public AuthAttribute(string profile) : base ("Auth")
{
this.ObjectName = profile;
}

public override void GetPropertiesForNewContext(IConstructionCallMessage ctorMsg)
{
ctorMsg.ContextProperties.Add(new AuthProperty());
//将这个自定义属性添加到AuthProperty的消息中
}
}

public class AuthProperty : IContextProperty, IContributeObjectSink
{
#region IContributeObjectSink implementation
public IMessageSink GetObjectSink(MarshalByRefObject o, IMessageSink next)
//将所提供的服务器对象的消息接收器连接到给定的接收器链前面
{
return new AuthAspect(next);
}
#endregion // IContributeObjectSink implementation

#region IContextProperty implementation
public string Name
{
get { return "AuthProperty"; }
}
public void Freeze(Context newContext)
{
}
public bool IsNewContextOK(Context newCtx)
{
return true;
}
#endregion //IContextProperty implementation
}

internal class AuthAspect : IMessageSink//定义一个消息接收器
{
internal AuthAspect(IMessageSink next)
{
m_next = next;
}

#region Private Vars
private IMessageSink m_next;
#endregion // Private Vars

#region IMessageSink implementation
public IMessageSink NextSink
{
get { return m_next; }
}

public IMessage SyncProcessMessage(IMessage msg)
{
Preprocess(msg);
IMessage returnMethod = m_next.SyncProcessMessage(msg);
return returnMethod;
}

public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
throw new InvalidOperationException();
}
#endregion //IMessageSink implementation

#region Helper methods
private void Preprocess(IMessage msg)
{
// We only want to process method calls
if (!(msg is IMethodMessage)) return;

IMethodMessage call = msg as IMethodMessage;
Type type = Type.GetType(call.TypeName);
string callStr = type.Name + "." + call.MethodName;
//Console.WriteLine("Security validating : {0} for {1}", callStr,Environment.UserName);
// call some security validating code

//MethodInfo m = (typeof(AttributeTest)).GetMethod(call.MethodName);

foreach(object t in call.Properties)
{
if(t is AuthAttribute)
{
AuthAttribute i = (AuthAttribute) t;
Console.WriteLine(i.ObjectName);
}
}

}

#endregion Helpers
}
}

我只是对自定义属性创建了一个新的构造函数,以接收用户的参数。

有一个问题我没有解决,就是我只能把这个属性作用到类上才可以起作用,但是如果作用到函数上就无法起作用了,还请高手指教啊!

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/14820420/viewspace-1016294/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/14820420/viewspace-1016294/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值