简体   繁体   中英

Unity 3.0 and Exception Logging

Need a sample project about Unity Exception Logging.

My Requirement is putting putting a class attribute with a return parameter to a class and let unity do all the work.

Such as I want this method to be logged in CustomExceptionHandler and return -1

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

  throw new Exception("TEST");

  }

Firstly, you will not be able to intercept a static method using Unity.

Take a look at the Developer's Guide to Dependency Injection Using Unity . Specifically, the chapter on Interception using Unity . Modifying and tailoring the code in the guide you might end up with something like:

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>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM