2013-08-20 105 views
0

需要關於Unity例外記錄的示例項目。Unity 3.0和例外記錄

我的要求是把具有返回參數的class屬性放到一個類中,讓unity統一起來做所有的工作。

比如我想在CustomExceptionHandler要記錄這種方法並返回-1

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

    throw new Exception("TEST"); 

    } 

回答

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

首先,您將無法使用Unity攔截靜態方法>>>>這是不好的。我不知道我將如何實施AOP。我需要一個免費的解決方案,它具有像postsharp這樣的功能。 –

+1

你可以看[後續](http://github.com/vc3/Afterthought)。那裏沒有很多免費的選擇。 –