2008-12-09 32 views
4

我冒險進入一些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 

我不得不承認我是很新的這一點,但它似乎是一個有趣的概念,我認爲我只需要指出正確的方向

回答

2

我把它通過擴展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

0

我已經使用OnMethodBoundaryAspect而不是ExceptionHandlerAspect沒有什麼問題。而且我還沒有讓我的密封。