1

我想使用 AOP 为我的所有方法记录异常。我创建了一个与以下相同的属性:

 [AttributeUsage(AttributeTargets.All)]
 public class ClsLogger : System.Attribute
 {
    private string _exMsg;
    public ClsLogger(string exMsg)
    {
        //
        // TODO: Add constructor logic here
        //
        _exMsg = exMsg;
        LogError();
    }
    public void LogError()
    {
        // This methods logs exception
        // Log Exception
    }
}

最后,我想使用此日志记录属性来记录我的应用程序方法的异常消息。我如何将异常消息传递给属性,因为它不是固定字符串而是可变的?有人可以帮忙吗?

4

1 回答 1

1

C# 中的属性在您调用之前不会实例化GetCustomAttributes,并且每次您这样做时它们都会实例化(请参阅 SO 上的这个问题)。

如果你想使用 AOP(如你的标题所示),那么你需要使用一些框架,比如PostSharpFodySheepAspect等。

如果您使用的是 ASP.NET MVC,那么您也可以使用一个内置ActionFilter类,但只能在 Controller 方法上使用。

于 2013-06-05T18:47:36.673 回答