使用PostSharp添加OnException属性

问题描述:

我冒险进入一些AOP,它似乎与.NET PostSharp是要走的路。使用PostSharp添加OnException属性

我想在发生异常时对db进行一些简单的日志记录。然而,我发现很难找到超出基本使用PostSharp的任何真正可靠的例子。我试过如下:

[Serializable] 
public sealed class LogExceptionAttribute : ExceptionHandlerAspect 
{ 
    public override void OnException(MethodExecutionEventArgs eventArgs) 
    { 
     //do some logging here 
    } 
} 

然后一个[LogException]属性附加到方法

但我得到一个编译错误:

Error 7 The type "CoDrivrBeta1.Classes.LogExceptionAttribute" or one of its ancestor should be decorated by an instance of MulticastAttributeUsageAttribute. C:\work\CoDrivrBeta1\CoDrivrBeta1\EXEC CoDrivrBeta1 

我不得不承认我是很新的这一点,但它似乎是一个有趣的概念,我认为我只需要指出正确的方向

我把它通过扩展OnExceptionAspect工作:

[Serializable] 
public sealed class LogExceptionAttribute : OnExceptionAspect 
{ 
    public override void OnException(MethodExecutionEventArgs eventArgs) 
    { 
     //do some logging here 
    } 
} 

原贴:

它希望你添加的组播特性:

[Serializable] 
[MulticastAttributeUsage(... Add Appropriate MulticastTargets ...)] 
public sealed class LogExceptionAttribute : ExceptionHandlerAspect 
{ 
    public override void OnException(MethodExecutionEventArgs eventArgs) 
    { 
     //do some logging here 
    } 
} 

见此链接更多详情: http://doc.postsharp.org/1.0/UserGuide/Laos/Multicasting/Overview.html

我已经使用OnMethodBoundaryAspect而不是ExceptionHandlerAspect没有什么问题。而且我还没有让我的密封。