需求:我们需要给已经开发好的服务如这里的UserService,添加额外的执行逻辑,但是又不想破坏原有的服务,如:我们需要给UserService添加监控逻辑,监控的目的是看UserService服务里的RegUser方法和GetUser方法的执行时间消耗

1、定义1个用户接口

namespace UnityConfigAOP
{
public interface IUserService
{
void RegUser(User user); User GetUser(User user);
}
}

2、实现用户这个接口

namespace UnityConfigAOP
{
public class UserService:IUserService
{
public void RegUser(User user)
{
Console.WriteLine("用户已注册。");
} public User GetUser(User user)
{
Console.WriteLine("得到用户信息。");
return user;
}
}
}

3、Unity配置文件
3.1、需要引用如下图这5个程序集

3.1、Unity.Config配置文件的注册顺序就是额外逻辑的调用顺序,然后才是业务方法本身,但是扩展逻辑可以是业务方法后

<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
<!--Microsoft.Practices.Unity.Configuration.UnityConfigurationSection-->
</configSections>
<unity>
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration"/>
<containers>
<container name="aopContainer">
<extension type="Interception"/>
<register type="UnityConfigAOP.IUserService,UnityConfigAOP" mapTo="UnityConfigAOP.UserService,UnityConfigAOP">
<interceptor type="InterfaceInterceptor"/>
<interceptionBehavior type="UnityConfigAOP.AOPBehavior.MonitorBehavior, UnityConfigAOP"/>
</register>
</container>
</containers>
</unity>
</configuration>

3.2、接口方法不需要某个AOP扩展怎么办呢?在方法上加个CustomNOAOPAttribute自定义属性,在执行MonitorBehavior类的Invoke方法里用特性input.Target.GetType().IsDefined(typeof(CustomNOAOPAttribute), true)去判断一下

3.3、MonitorBehavior监控行为额外逻辑代码

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Unity.Interception.InterceptionBehaviors;
using Unity.Interception.PolicyInjection.Pipeline; namespace UnityConfigAOP.AOPBehavior
{
/// <summary>
/// 性能监控的AOP扩展
/// </summary>
public class MonitorBehavior : IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
} public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
var type = input.Target.GetType();
string methodName = input.MethodBase.Name;
if (type.IsDefined(typeof(CustomNOAOPAttribute), true))
{
var method = getNext().Invoke(input, getNext);//后续逻辑执行
return method;
} MethodInfo currentMethod = type.GetMethod(methodName);
if (currentMethod.IsDefined(typeof(CustomNOAOPAttribute), true))//检查方法有没有定义此属性
{
var method = getNext().Invoke(input, getNext);//后续逻辑执行
return method;
} Console.WriteLine(this.GetType().Name);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start(); var methodReturn = getNext().Invoke(input, getNext);//后续逻辑执行 stopwatch.Stop();
Console.WriteLine($"{this.GetType().Name}统计方法{methodName}执行耗时{stopwatch.ElapsedMilliseconds}ms"); return methodReturn;
} public bool WillExecute
{
get { return true; }
}
}
}

4、客户端调用UserService服务

namespace UnityConfigAOP
{
class Program
{
static void Main(string[] args)
{
User user = new User()
{
Name = "David.Meng",
Password = ""
};
//配置UnityContainer
IUnityContainer container = new UnityContainer();
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config");
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); UnityConfigurationSection configSection = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
configSection.Configure(container, "aopContainer"); IUserService userService = container.Resolve<IUserService>();
userService.RegUser(user);
userService.GetUser(user);
}
}
}

5、调试代码
执行userService.RegUser(user);代码的时候,并没有直接进入到RegUser(User user);方法里面,而是先进到MonitorBehavior类的Invoke方法里,直到执行到getNext().Invoke(input, getNext);这句代码才真正的进入到RegUser(User user);方法里面

7、项目截图,我们可以配置多个AOP行为不光是监控行为,还可以配置日志行为,异常行为,缓存行为等等,如下图所示

6、UnityConfig实现AOP的更多相关文章

  1. 第七节:WebApi与Unity整合进行依赖注入和AOP的实现

    一. IOC和DI 1. 通过Nuget引入Unity程序集. PS:[版本:5.8.6] 2. 新建DIFactory类,用来读取Unity的配置文件并创建Unity容器,需要注意的是DIFacto ...

  2. 基于spring注解AOP的异常处理

    一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...

  3. Spring基于AOP的事务管理

                                  Spring基于AOP的事务管理 事务 事务是一系列动作,这一系列动作综合在一起组成一个完整的工作单元,如果有任何一个动作执行失败,那么事务 ...

  4. 学习AOP之透过Spring的Ioc理解Advisor

    花了几天时间来学习Spring,突然明白一个问题,就是看书不能让人理解Spring,一方面要结合使用场景,另一方面要阅读源代码,这种方式理解起来事半功倍.那看书有什么用呢?主要还是扩展视野,毕竟书是别 ...

  5. 学习AOP之深入一点Spring Aop

    上一篇<学习AOP之认识一下SpringAOP>中大体的了解了代理.动态代理及SpringAop的知识.因为写的篇幅长了点所以还是再写一篇吧.接下来开始深入一点Spring aop的一些实 ...

  6. 学习AOP之认识一下Spring AOP

    心碎之事 要说知道AOP这个词倒是很久很久以前了,但是直到今天我也不敢说非常的理解它,其中的各种概念即抽象又太拗口. 在几次面试中都被问及AOP,但是真的没有答上来,或者都在面上,这给面试官的感觉就是 ...

  7. .Net中的AOP系列之构建一个汽车租赁应用

    返回<.Net中的AOP>系列学习总目录 本篇目录 开始一个新项目 没有AOP的生活 变更的代价 使用AOP重构 本系列的源码本人已托管于Coding上:点击查看. 本系列的实验环境:VS ...

  8. .NET里简易实现AOP

    .NET里简易实现AOP 前言 在MVC的过滤器章节中对于过滤器的使用就是AOP的一个实现了吧,时常在工作学习中遇到AOP对于它的运用可以说是很熟练了,就是没想过如果自己来实现的话是怎么实现的,性子比 ...

  9. 在.Net中实现自己的简易AOP

    RealProxy基本代理类 RealProxy类提供代理的基本功能.这个类中有一个GetTransparentProxy方法,此方法返回当前代理实例的透明代理.这是我们AOP实现的主要依赖. 新建一 ...

随机推荐

  1. Hystrix完整配置列表

    前提 Hystrix在2018年11月20日之后已经停止维护,最后一个提交记录是:Latest commit 3cb2158 on 20 Nov 2018,最后一个正式版本为1.5.18.鉴于目前所在 ...

  2. F#周报2019年第48期

    新闻 拥抱可空引用类型 介绍Orleans 3.0 视频及幻灯片 组合的力量 关于.NET:探索新的用于.NET的Azure .NET SDK .NET设计审查:GitHub快速审查 FableCon ...

  3. 插入节点(appendChild())

    appendChild():方法将给元素节点追加一个子节点: reference = element.appendChild(newChild); 如上所示,给定节点newChild将成为给定元素节点 ...

  4. String s = "a";与String s = new String("a")的区别

    String s1 = "a" 时,首先会在字符串常量池中查找有无 “a” 这个对象. 若没找到,就创建一个 "a" 对象, 然后,以 s1 为它的引用.若在字 ...

  5. Chapter 05—Advanced data management(Part 2)

    二. 控制流 statement:一个单独的R语句或者是一个复合的R语句: cond:条件表达式,为TRUE或FALSE: expr:数字或字符表达式: seq:数字或字符串的顺序. 1.循环语句:f ...

  6. builtins内建模块

    builtins模块 为啥我们没有导入任何模块就能使用len(),str(),print()...等这么多的函数? 其实在我们运行python解释器的时候,他会自动导入一些模块,这些函数就是从这些地方 ...

  7. java抽象类,接口(接口定义,实现接口,instanceof运算符,对象转换)

    抽象类 在面向对象的概念中,所有的对象都是通过类来表述的,但并不是所有的类都能够完整的描绘对象,如果一个类中没有包含足够的信息来描绘一类具体的对象,这样的类就是抽象类.抽象类往往用来表征对问题领域进行 ...

  8. shell 往文件中添加一列一样的字符串

    例如:往文件file.txt中,添加一列字符串"20161020", 用制表符分割 awk '$0=$0"\t20161020"' file.txt

  9. NSDateFormatter格式详细列表一览

    转自:http://www.cnblogs.com/xinus/archive/2012/10/29/NSDateFormatter_samples.html 前言:iOS开发中NSDateForma ...

  10. 基于Java语言的IO操作(文件复制)

    public static void main(String[] args) { //获取复制开始前系统时间毫秒值 long start=System.currentTimeMillis(); //文 ...