【问题标题】:Adding an OnException attribute using PostSharp使用 PostSharp 添加 OnException 属性
【发布时间】:2008-12-09 11:56:21
【问题描述】:

我正在探索一些 AOP,似乎使用 .NET PostSharp 是要走的路。

我想在发生异常时对数据库进行一些简单的日志记录。但是,我发现很难找到除基础知识之外使用 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

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

【问题讨论】:

    标签: c# logging aop postsharp


    【解决方案1】:

    我通过扩展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

    【讨论】:

      【解决方案2】:

      我使用 OnMethodBoundaryAspect 而不是 ExceptionHandlerAspect 没有问题。而且我的也没有密封。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多