Unity The Tag Attribute Matching Rule

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<Interception>()
25   .AddPolicy(“TagAttributeMatchingRule”)
26   .AddMatchingRule(new TagAttributeMatchingRule(“Test”))
27   .AddCallHandler<Log4NetHandler>();
28 unityContainer.RegisterType<MyObject>(
29   new Interceptor<VirtualMethodInterceptor>(),
30   new InterceptionBehavior<PolicyInjectionBehavior>()
31 );
32 
33 MyObject myObject = unityContainer.Resolve<MyObject>();
34 
35 myObject.DoWork(Int32.MaxValue, Char.MaxValue);
36 myObject.DoWork2(Int32.MaxValue, Char.MaxValue);
37 myObject.DoWork3();
复制代码

配置文件定义如下:

复制代码
<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” />

    <interception>
      <policy name=”TagAttributePolicy”>
        <matchingRule name=”TagAttributeMatchingRule” type=”TagAttributeMatchingRule”>
          <constructor>
            <param name=”tagToMatch” value=”Test” />
          </constructor>
        </matchingRule>
        <callHandler name=”Log4NetHandler” type=”Log4NetHandler” />
      </policy>
    </interception>

    <register type=”MyObject”>
      <interceptor type=”VirtualMethodInterceptor” />
      <interceptionBehavior type=”PolicyInjectionBehavior” />
    </register>
  </container>
</unity>
复制代码
posted @   junchu25  阅读(399)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示