Unity提供了函数入口参数类型匹配的规则ParameterTypeMatchingRule类型。它可以针对一些特定函数的入口参数进行拦截,比如拦截入口参数类型为Int32和Char的函数,看一个简单示例:
1 public class MyObject 2 { 3 public virtual void DoWork(Int32 i, Char c) 4 { 5 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 ParameterTypeMatchingInfo[] paramsUsed = new ParameterTypeMatchingInfo[]24 {25 new ParameterTypeMatchingInfo(“System.Int32″, false, ParameterKind.Input),26 new ParameterTypeMatchingInfo(“System.Char”, false, ParameterKind.Input)27 };28 29 unityContainer.Configure()30 .AddPolicy(“ParameterTypeMatchingRule”)31 .AddMatchingRule(new ParameterTypeMatchingRule(paramsUsed))32 .AddCallHandler ();33 unityContainer.RegisterType (34 new Interceptor (),35 new InterceptionBehavior ()36 );37 38 MyObject myObject = unityContainer.Resolve ();39 40 myObject.DoWork(Int32.MaxValue, Char.MaxValue);41 myObject.DoWork2(Int32.MaxValue, Char.MaxValue);42 myObject.DoWork3();
只有MyObject的DoWork和DoWork2函数符合定义的ParameterTypeMatchingRule。虽然ParameterTypeMatchingInfo允许定义返回值和它的类型,但是在ParameterTypeMatchingRule中无效。看一个简单的例子:
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 ParameterTypeMatchingInfo[] paramsUsed = new ParameterTypeMatchingInfo[]24 {25 new ParameterTypeMatchingInfo(“System.Int32″, false, ParameterKind.Input),26 new ParameterTypeMatchingInfo(“System.Char”, false, ParameterKind.Input),27 new ParameterTypeMatchingInfo(“System.Int32″, false, ParameterKind.ReturnValue)28 };29 30 unityContainer.Configure()31 .AddPolicy(“ParameterTypeMatchingRule”)32 .AddMatchingRule(new ParameterTypeMatchingRule(paramsUsed))33 .AddCallHandler ();34 unityContainer.RegisterType (35 new Interceptor (),36 new InterceptionBehavior ()37 );38 39 MyObject myObject = unityContainer.Resolve ();40 41 myObject.DoWork(Int32.MaxValue, Char.MaxValue);42 myObject.DoWork2(Int32.MaxValue, Char.MaxValue);43 myObject.DoWork3();
虽然添加了返回值类型的限制,但是DoWork2依然被拦截注入。一般来说我们可以通过ParameterTypeMatchingRule跟踪那些使用句柄的函数。ParameterTypeMatchingRule的构造比较麻烦,首先它的构造函数接受IEnumerable<ParameterTypeMatchingInfo>类型,需要注册一个List<ParameterTypeMatchingInfo>去实现。然后通过method定义Add函数添加一个一个ParameterTypeMatchingInfo。配置文件定义如下: