2017-09-24 118 views
2

我想獲得回答here中描述的行爲,但是通過代碼使用配置。代碼示例顯示正在創建的自定義屬性,沒有任何統一關聯,並通過配置添加行爲。使用自定義屬性的.NET Unity攔截

自定義屬性位於同一解決方案中引用的單獨程序集中。

問題是,它配置期間拋出異常:

InvalidOperationException異常:類型Microsoft.Practices.Unity.InterceptionExtension.CustomAttributeMatchingRule沒有一個構造函數的參數(LogAttribute,布爾值)。

container 
    .AddNewExtension<Interception>() 
    .Configure<Interception>() 
     .AddPolicy("MyLoggingPolicy") 
     .AddMatchingRule<CustomAttributeMatchingRule>(
     new InjectionConstructor(typeof(Abstractions.Attributes.LogAttribute), true)) 
     .AddCallHandler<LoggingHandler>(new ContainerControlledLifetimeManager()) 
      .Interception 
      .Container 
     .RegisterType<IFirstInterface>(new InjectionFactory((context) => FirstClassFactoryMethod())) 
     .RegisterType<ISecondInterface>(new InjectionFactory((context) => SecondClassFactoryMethod())); 

[AttributeUsage(AttributeTargets.Method)] 
public class LogAttribute : Attribute { } 

public class LoggingHandler : ICallHandler 
{ 
    public int Order { get; set; } 

    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) 
    { 
     Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")} Started: {input.MethodBase.Name}"); 
     var result = getNext()(input, getNext); 
     Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")} Completed: {input.MethodBase.Name}"); 
     return result; 
    } 
} 

更新拋出到行:

.AddMatchingRule(
    new CustomAttributeMatchingRule(typeof(Abstractions.Attributes.LogAttribute), true)) 

防止被拋出的異常,但LoggingHandler不會收到從具有[日誌]屬性的方法的任何呼叫。

注意:用[Log]標記的方法是公共方法,在不同的程序集中,在使用.Resolve()實例化的類中。

+0

難道你攔截方法不是虛擬的或不是一個接口定義的一部分,或者你將它們解析爲具體類型而不是接口?因爲這會阻止攔截 –

+0

@vasiloreshenski它是接口定義的一部分。我解決它像上面顯示:.RegisterType (新InjectionFactory((上下文)=> FirstClassFactoryMethod()))。它仍然需要虛擬嗎? – Filip

回答

3

對於任何人都遇到了同樣的問題 - 我必須定義在註冊類型的攔截行爲:

.RegisterType<IFirstInterface>(
    new InjectionFactory((context) => FirstClassFactoryMethod()) 
    new Interceptor<TransparentProxyInterceptor>() 
    new InterceptionBehavior<PolicyInjectionBehavior>()) 
.RegisterType<ISecondInterface>(
    new InjectionFactory((context) => SecondClassFactoryMethod()) 
    new Interceptor<TransparentProxyInterceptor>() 
    new InterceptionBehavior<PolicyInjectionBehavior>()));