Unity提供了用于匹配函数名称和类型签名的规则MethodSignatureMatchingRule类型。ParameterTypeMatchingRule用于匹配函数的参数类型和参数性质(In、Out),但是无法匹配函数名称。而MethodSignatureMatchingRule的缺点是无法限制参数性质。看一个简单示例:
1 public class MyObject 2 { 3 public virtual Int32 DoWork(Int32 i, Char c) 4 { 5 return i; 6 } 7 8 public virtual void DoWork2(Int32 i, Char c) 9 { 10 11 } 12 13 public virtual void DoWork3() 14 { 15 16 } 17 } 18 19 IUnityContainer unityContainer = new UnityContainer(); 20 21 unityContainer.LoadConfiguration(); 22 23 String[] paramTypeNames = new String[] { “System.Int32″, “System.Char” }; 24 25 unityContainer.Configure<Interception>() 26 .AddPolicy(“MethodSignatureMatchingRule”) 27 .AddMatchingRule(new MethodSignatureMatchingRule(“DoWork*”, paramTypeNames)) 28 .AddCallHandler<Log4NetHandler>(); 29 unityContainer.RegisterType<MyObject>( 30 new Interceptor<VirtualMethodInterceptor>(), 31 new InterceptionBehavior<PolicyInjectionBehavior>() 32 ); 33 34 MyObject myObject = unityContainer.Resolve<MyObject>(); 35 36 myObject.DoWork(Int32.MaxValue, Char.MaxValue); 37 myObject.DoWork2(Int32.MaxValue, Char.MaxValue); 38 myObject.DoWork3();
相比ParameterTypeMatchingRule,MethodSignatureMatchingRule结合了ParameterTypeMatchingRule和MemberNameMatchingRule的功能,只是它无法限制参数的性质是In、Out。配置文件定义如下:
<unity xmlns=”http://schemas.microsoft.com/practices/2010/unity”> <sectionExtension type=”Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration” /> <assembly name=”mscorlib, 2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ /> <assembly name=”Microsoft.Practices.Unity.Interception” /> <assembly name=”UnityTest6″ /> <namespace name=”System” /> <namespace name=”System.Collections.Generic” /> <namespace name=”Microsoft.Practices.Unity.InterceptionExtension” /> <namespace name=”UnityTest6″ /> <container> <extension type=”Interception” /> <register name=”paramTypeNames” type=”IEnumerable[String]” mapTo=”List[String]“> <constructor /> <method name=”Add”> <param name=”item” value=”System.Int32″ /> </method> <method name=”Add”> <param name=”item” value=”System.Char” /> </method> </register> <interception> <policy name=”MethodSignaturePolicy”> <matchingRule name=”MethodSignatureMatchingRule” type=”MethodSignatureMatchingRule”> <constructor> <param name=”methodName” value=”DoWork*” /> <param name=”parameterTypeNames” dependencyName=”paramTypeNames” /> </constructor> </matchingRule> <callHandler name=”Log4NetHandler” type=”Log4NetHandler” /> </policy> </interception> <register type=”MyObject”> <interceptor type=”VirtualMethodInterceptor” /> <interceptionBehavior type=”PolicyInjectionBehavior” /> </register> </container> </unity>