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!