1. 程式人生 > >采用PostSharp實現

采用PostSharp實現

odex n! ride ces nbsp string rri aspect body

1、創建控制臺程序

2、通過Nuget添加PostSharp引用

3、定義註入類(實現方法的Entry,Exit,Exception,Success功能),如:

[Serializable]
class MyAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
Console.WriteLine("On Entry!");
}

public override void OnExit(MethodExecutionArgs args)
{
Console.WriteLine("On Exit!");
}

public override void OnException(MethodExecutionArgs args)
{
Console.WriteLine("On Exception!");
}

public override void OnSuccess(MethodExecutionArgs args)
{
Console.WriteLine("On Success!");
}
}

4、定義一個業務類,並在方法上添加【註入類】屬性,如:

class MyClass
{
[MyAspect]
public void MyMethod()
{
Console.WriteLine("Hello,AOP!");
}
}

5、在Main中使用業務類,如:

class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.MyMethod();
Console.Read();
}
}

6、運行,輸出:

On Entry!
Hello,AOP!
On Success!
On Exit!

采用PostSharp實現