Unity通过TagAttribute显示定义需要被拦截注入的成员,TagAttributeMatchingRule类型用来匹配该规则。需要注意的是TagAttributeMatchingRule不支持通配符。看一个简单的例子:
1 public class MyObject 2 { 3 [Tag("Test")] 4 public virtual Int32 DoWork(Int32 i, Char c) 5 { 6 return i; 7 } 8 9 [Tag("Test2")]10 public virtual void DoWork2(Int32 i, Char c)11 {12 13 }14 15 public virtual void DoWork3()16 {17 18 }19 }20 21 IUnityContainer unityContainer = new UnityContainer();22 23 unityContainer.LoadConfiguration();24 unityContainer.Configure()25 .AddPolicy(“TagAttributeMatchingRule”)26 .AddMatchingRule(new TagAttributeMatchingRule(“Test”))27 .AddCallHandler ();28 unityContainer.RegisterType (29 new Interceptor (),30 new InterceptionBehavior ()31 );32 33 MyObject myObject = unityContainer.Resolve ();34 35 myObject.DoWork(Int32.MaxValue, Char.MaxValue);36 myObject.DoWork2(Int32.MaxValue, Char.MaxValue);37 myObject.DoWork3();
配置文件定义如下: