Creating Policy Injection Matching Rules
Unity可以定于拦截的匹配策略,只要你实现了IMatchingRule接口。我们可以根据实际中框架的不同需求,开发不同的MatchingRule。比如Unity自带的TypeMatchingRule只能够匹配给定的类型,但是无法匹配当前类型的基类型。只要当前类型或者它继承的类型层次结构上等于某个特定类型,它就可以被拦截。看一个实现IMatchingRule接口的示例:
1 public sealed class HierarchicalTypeMatchingRule : IMatchingRule 2 { 3 private readonly Lazy<Type> m_targetType; 4 private readonly String m_typeName; 5 6 public HierarchicalTypeMatchingRule(String typeName) 7 { 8 m_typeName = typeName; 9 m_targetType = new Lazy<Type>(() => Type.GetType(m_typeName)); 10 } 11 12 private Type TargetType 13 { 14 get 15 { 16 return m_targetType.Value; 17 } 18 } 19 20 #region IMatchingRule Members 21 22 public Boolean Matches(MethodBase member) 23 { 24 Type type = member.ReflectedType; 25 Type targetType = this.TargetType; 26 27 while (type != targetType) 28 type = type.BaseType; 29 30 return (type == targetType); 31 } 32 33 #endregion 34 } 35 36 public sealed class ConsoleOutHandler : ICallHandler 37 { 38 #region ICallHandler Members 39 40 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) 41 { 42 Console.WriteLine(input.MethodBase.Name); 43 44 return getNext()(input, getNext); 45 } 46 47 public Int32 Order { get; set; } 48 49 #endregion 50 } 51 52 public class MyObject 53 { 54 public virtual void DoWork() 55 { 56 57 } 58 } 59 60 IUnityContainer unityContainer = new UnityContainer(); 61 62 unityContainer.LoadConfiguration(); 63 unityContainer.Configure<Interception>() 64 .AddPolicy(“HierarchicalTypeMatchingRule”) 65 .AddMatchingRule(new HierarchicalTypeMatchingRule(“UnityTest7.MyObject, UnityTest7″)) 66 .AddCallHandler<ConsoleOutHandler>(); 67 unityContainer.RegisterType<MyObject>( 68 new Interceptor<VirtualMethodInterceptor>(), 69 new InterceptionBehavior<PolicyInjectionBehavior>() 70 ); 71 72 MyObject myObject = unityContainer.Resolve<MyObject>(); 73 74 myObject.DoWork();