C# 面向方面 通过Attribute 拦截从而扩展方法

本文介绍了如何使用C#的面向方面编程(AOP)来扩展方法。通过创建特性(Attribute)、在Service方法上应用、编写拦截器以及配置Spring.NET的XML,实现对特定方法的拦截和扩展功能。示例中展示了如何定义TestAttribute,添加到GetTest方法上,并通过TestInterceptor进行方法拦截。
摘要由CSDN通过智能技术生成

1.创建特性

 [AttributeUsage(AttributeTargets.Method)]
    public class TestAttribute:Attribute
    {
    }

 

2.在Service中所要拦截的方法上加入属性

[Test]
  public Image GetTest()

{

 

}

3.编写拦截的扩展方法

using AopAlliance.Intercept

namespace Test

{
    public class TestInterceptor:IMethodInterceptor
    {
        public object Invoke(IMethodInvocation invocation)
        {
            using (new TestFunc())    //扩展方法
            {
                return invocation.Proceed();
            }
        }
    }
}

4.service.xml 中配置关联

<object id="TestService" type="Spring.Aop.Framework.ProxyFactoryObject"  >
  <property name="Target">
   <object type="Service.TestService.Service">
    <property name="testDao" ref="testDao" />    //SERVICE注入的DAO
   </object>
  </property>
  <property name="InterceptorNames">
   <!--<idref local="IdentityPersonateAttributedAdvisor" />-->
   <list>
    <value>TestAttributedAdvisor</value>
   </list>
  </property>
 </object>

<!--<object id="TestAttributedAdvisor" type="Spring.Aop.Support.AttributeMatchMethodPointcutAdvisor, Spring.Aop">
  <property name="Advice" ref="testAspect"/>
  <property name="Attribute" value="Attribute.TestAttribute, Attribute" />
 </object>       这种方法也可以-->

5.专门拦截的XML

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<!--线程伪装-->
<object id="testAspect" type="Attribute.TestInterceptor,Attribute" >
</object>

 <object id="TestAttributedAdvisor" type="Spring.Aop.Support.AttributeMatchMethodPointcutAdvisor, Spring.Aop">
  <property name="Advice" ref="testAspect"/>
  <property name="Attribute" value="Attribute.TestAttribute, Attribute" />
 </object>
</objects>

======================================================================

方法2 针对具体SERVICE下的方法

<object id="CaseDurationPointcut" type="Spring.Aop.Support.SdkRegularExpressionMethodPointcut, Spring.Aop">

    <!--<property name="pattern" value="GCDF.RecruitWorkflow.Service.CaseServiceProxy.*"/>-->

    <!--pattern属性为拦截表达式。Service.*的意思是,拦截Service命名空间下(包括子空间)的所有类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值