你應該有你的實例已經...
container.Register(Component.For<IInterceptor>().ImplementedBy<Logger>().Named("myinterceptor"));
然後,你將用攔截器的屬性裝飾每個類。
[Interceptor("myinterceptor")]
public class Logger : IInterceptor
{
public void Intercept(IInvocation invocation) {
Console.WriteLine(">> type in <<");
invocation.Proceed();
Console.WriteLine(">> type out <<");
}
}
如果實施攔截,你就能知道哪種類型的,因爲你已經定義了這樣的橫切關注點由攔截器來解決解決。
我想你想讓你的攔截器知道所有需要攔截器的合約,而不是所有類型的攔截器的指令。我希望這有幫助!!
編輯:這是我如何使用統一到記錄儀:
Public Class LoggingInterceptionBehavior
Implements IInterceptionBehavior
Public Function Invoke(input As IMethodInvocation, getNext As GetNextInterceptionBehaviorDelegate) As IMethodReturn Implements IInterceptionBehavior.Invoke
' Before invoking the method on the original target.
Dim icp As ClaimsPrincipal = TryCast(Thread.CurrentPrincipal, ClaimsPrincipal)
' Access IClaimsIdentity which contains claims
Dim claimsIdentity As ClaimsIdentity = DirectCast(icp.Identity, ClaimsIdentity)
Dim param = GetParam(input)
If claimsIdentity IsNot Nothing Then
If param IsNot Nothing Then
WriteLog([String].Format("{0} is invoking method {1} at {2} with a parameter of {3}", claimsIdentity.Name, input.MethodBase, DateTime.Now.ToLongTimeString(), param))
Else
WriteLog([String].Format("{0} is invoking method {1} at {2} without a parameter", claimsIdentity.Name, input.MethodBase, DateTime.Now.ToLongTimeString()))
End If
Else
'no claim
WriteLog([String].Format("NO CLAIM Invoking method {0} at {1} with a parameter of {2}", input.MethodBase, DateTime.Now.ToLongTimeString(), param))
End If
' Invoke the next behavior in the chain.
Dim result = getNext()(input, getNext)
' After invoking the method on the original target.
If result.Exception IsNot Nothing Then
WriteCriticalLog([String].Format("Method {0} threw exception {1} at {2}", input.MethodBase, result.Exception.Message, DateTime.Now.ToLongTimeString()))
Else
WriteLog([String].Format("Method {0} returned {1} at {2}", input.MethodBase, result.ReturnValue, DateTime.Now.ToLongTimeString()))
End If
Return result
End Function
End Class
我如何註冊他們:
container.RegisterType(Of IXXXService, XXXService)(New Interceptor(Of InterfaceInterceptor)(),
New InterceptionBehavior(Of LoggingInterceptionBehavior))
非常感謝,正是我一直在尋找的。是否也可以在這個地方獲得對InvocationTarget的引用? (與Intercept-method中的IInvocation.InvocationTarget相同?)。我無法在ComponentModel中找到等效屬性。 – user2959547