Unity 3.0和异常日志记录

时间:2013-08-20 07:24:34

标签: c# unity-container decorator postsharp aop

需要有关Unity异常日志记录的示例项目。

我的要求是将一个带有返回参数的class属性放到一个类中,让unity完成所有的工作。

比如我希望在CustomExceptionHandler中记录此方法并返回-1

  [CustomExceptionHandler(-1)]
  public static int process(){

  throw new Exception("TEST");

  }

1 个答案:

答案 0 :(得分:0)

首先,您将无法使用Unity拦截静态方法。

看看Developer's Guide to Dependency Injection Using Unity。具体来说,是关于Interception using Unity的章节。修改和定制指南中的代码可能最终会出现以下内容:

class CustomExceptionHandler : ICallHandler
{
  public IMethodReturn Invoke(IMethodInvocation input,
    GetNextHandlerDelegate getNext)
  {
    WriteLog(String.Format("Invoking method {0} at {1}",
      input.MethodBase, DateTime.Now.ToLongTimeString()));

    // Invoke the next handler in the chain
    var result = getNext().Invoke(input, getNext);

    // After invoking the method on the original target
    if (result.Exception != null)
    {
      // This could cause an exception if the Type is invalid
      result.ReturnValue = -1;
      result.Exception = null;    
    }

    return result;
  }

  public int Order
  {
    get;
    set;
  }
}


class CustomExceptionHandlerAttribute : HandlerAttribute
{
  private readonly int order;

  public CustomExceptionHandlerAttribute(int order)
  {
    this.order = order;
  }

  public override ICallHandler CreateHandler(IUnityContainer container)
  {
    return new CustomExceptionHandler() { Order = order };
  }
}

class TenantStore : ITenantStore
{
    [CustomExceptionHandler(1)]
    public int Process()
    {
        throw new Exception("TEST");
    }
}

container.RegisterType<ITenantStore, TenantStore>(
    new InterceptionBehavior<PolicyInjectionBehavior>(),
    new Interceptor<InterfaceInterceptor>());