Unity The Return Type Matching Rule

之前提到Unity提供的ParameterTypeMatchingRule无法定义返回值,ReturnTypeMatchingRule就是用来完成限制这个条件。看一个简单的示例:

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

MyObject中只有函数DoWork的返回值匹配了定义,配置文件定义如下:

<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=”ReturnTypePolicy”>
        <matchingRule name=”ReturnTypeMatchingRule” type=”ReturnTypeMatchingRule”>
          <constructor>
            <param name=”returnTypeName” value=”System.Int32″ />
          </constructor>
        </matchingRule>
        <callHandler name=”Log4NetHandler” type=”Log4NetHandler” />
      </policy>
    </interception>

    <register type=”MyObject”>
      <interceptor type=”VirtualMethodInterceptor” />
      <interceptionBehavior type=”PolicyInjectionBehavior” />
    </register>
  </container>
</unity>
posted @ 2012-08-11 10:34  junchu25  阅读(305)  评论(0编辑  收藏  举报