第一次AOP,附上使用DEMO,可用在简单生产环境了

时间:2022-05-22 17:00:47

demo代码如下

 1     public class ConsoleTimeAttribute : ApectBaseAttribute
2 {
3 public override void Before(ApectContext apectContext)
4 {
5 apectContext.SetCorrelationObject(DateTime.Now);
6 Console.WriteLine($"Before > Method:{apectContext.MethodName} > {DateTime.Now}");
7 }
8
9 public override void After(ApectContext apectContext)
10 {
11 Console.WriteLine($"Before > Method:{apectContext.MethodName} > {DateTime.Now}");
12 Console.WriteLine($"CorrelationObject > {(DateTime)apectContext.CorrelationObject}");
13 }
14 }

先是继承ApectBaseAttribute的特性类,等会用;

1 public interface ITest
2 {
3 [ConsoleTime]//加了特性监控
4 void Say(string message);
5 }
    public class Test : ITest
{
private readonly string _init;

public Test(string init)
{
_init
= init;
}

public void Say(string message)
{
Console.WriteLine($
"init : {_init} || message : {message}");
}
}

以下开始怎么使用AOP

var type = ApectProxyBuilder.BuildType<ITest>(typeof(Test));
ITest test
= (ITest) Activator.CreateInstance(type,"ok");
test.Say(
"说点什么");

如果配合IOC就能完美使用,记得目前还是只能提供学习,还缺少AOP代理类里执行方法有返回值的返回,还有只代理非继承接口类的AOP处理。

如果有什么疑问和不妥之处欢迎多多交流,后期会运用到生产环境

2017.2.22 已经可用在简单生产环境了,使用当中有什么疑问,可联系我,联系信息在GIT库页面上有

GIT代码地址:https://git.oschina.net/ruanjianfeng/Ruan.Framework.Core