【问题标题】:Unity 3.0 and Exception LoggingUnity 3.0 和异常记录
【发布时间】:2013-08-20 07:24:33
【问题描述】:

需要一个关于 Unity 异常记录的示例项目。

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

比如我想让这个方法登录到CustomExceptionHandler并返回-1

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

  throw new Exception("TEST");

  }

【问题讨论】:

    标签: c# unity-container decorator postsharp aop


    【解决方案1】:

    首先,您将无法使用 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>());
    

    【讨论】:

    • 首先,您将无法使用 Unity 拦截静态方法。>>>> 这很糟糕。我不知道我将如何实现 AOP。我需要一个具有 postsharp 等功能的免费解决方案。
    • 你可以看看Afterthough。那里没有很多免费的替代品。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2011-11-25
    相关资源
    最近更新 更多