基于微软企业库的AOP组件(含源码)
软件开发,离不开对日志的操作。日志可以帮助我们查找和检测问题,比较传统的日志是在方法执行前或后,手动调用日志代码保存。但自从AOP出现后,我们就可以避免这种繁琐但又必须要实现的方式。本文是在微软企业库的AOP基础上封装出的组件。注意:是使用2.0版本,因为2.0以上版本是基于Net4.5类库的。好了,废话不多说。如图-1所示
图-1
说明
logmethodBillModel文件,是记录AOP详细信息
IBasicCodeService和BasicCodeService是用于测试的接口和实现类
AopUtil是实现Aop的类,核心代码
继续分析代码。
步骤1,先创建2个特性,用于标记在类和方法上,表示这个类中这个方法需要被Aop记录
/// <summary>
/// 贴在接口上
/// </summary>
public class NSAopHandlerAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
{
return new NSAopCallHandler();
}
} /// <summary>
/// 贴在方法上,作用:用于开启AOP功能
/// 开启AOP日志保存
/// </summary>
public class NSAopMethodToMethodHandlerAttribute : System.Attribute
{
}
步骤2,继承ICallHandler接口实现Aop功能
public class NSAopCallHandler : ICallHandler
{
public int Order { get; set; } public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
//增加其他日志类型,处理方案如下
//无论是否需记录log_method方法,方法均先执行完成.同时,记录时执行时间 MethodBase mbCurrent = input.MethodBase;
string methodName = input.MethodBase.Name;
string fullName = input.Target.ToString() + "." + methodName; //1,方法执行,并记录开始和结束执行时间
DateTime dtmBegin = DateTime.Now;
var methodReturn = getNext()(input, getNext);
DateTime dtmEnd = DateTime.Now; TimeSpan ts = dtmEnd - dtmBegin;
decimal invokeMilliSecond = Convert.ToDecimal(ts.TotalMilliseconds); //6,判断是否需保存Aop日志
object attriToMethod = AttributeHelper.GetCustomAttribute(mbCurrent, "NSAopMethodToMethodHandlerAttribute");
if (attriToMethod != null )
{
string declaringType = input.MethodBase.ToString();
string instanceName = input.MethodBase.Module.Name; //获取参数列表
Dictionary<string, string> dicParamInfo = new Dictionary<string, string>();
for (var i = 0; i < input.Arguments.Count; i++)
{
string piName = input.Arguments.ParameterName(i);
string piValue = input.Arguments[i] as string;
dicParamInfo.Add(piName, piValue);
} //获取方法的层级关系
//参考地址:http://www.cnblogs.com/mumuliang/p/3939143.html
string parentFullName = null;
string parentDeclaringType = null;
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
System.Diagnostics.StackFrame[] sfs = st.GetFrames();
for (int u = 0; u < sfs.Length; ++u)
{
System.Reflection.MethodBase mb = sfs[u].GetMethod(); //数据如下所示
//[CALL STACK][12]: ExampleAOP.AOPProxy.BasicCodeService.DoSomething1
//[CALL STACK][13]: ExampleAOP.AOPProxy.AOPProxyTest.Output
//[CALL STACK][14]: ExampleAOP.Program.Main
string parentInfo = string.Format("[CALL STACK][{0}]: {1}.{2}", u, mb.DeclaringType.FullName, mb.Name); //判断是否包含本方法.若包含,则获取其下一级的数据即可
string source = mb.Name;
if (source == methodName)
{
if (u + 1 < sfs.Length)
{
System.Reflection.MethodBase mbParent = sfs[u + 1].GetMethod(); parentFullName = mbParent.DeclaringType.FullName + "." + mbParent.Name;
parentDeclaringType = mbParent.ToString();
} break;
}
} //记录至全局静态变量
logmethodBillModel modelLog = new logmethodBillModel()
{
MethodName = methodName,
FullName = fullName,
DeclaringType = declaringType,
ParentFullName = parentFullName,
ParentDeclaringType = parentDeclaringType,
ParamInfo = dicParamInfo,
InvokeBeginTime = dtmBegin,
InvokeEndTime = dtmEnd,
InvokeMilliSecond = invokeMilliSecond,
InstanceName = instanceName,
};
BaseService.LogMethods.Add(modelLog);
} return methodReturn;
}
}
步骤3,就是对接口的使用,当然这里用的是IOC。如下代码所示
/// <summary>
/// 创建Service服务类,基于微软企业库
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T CreateService<T>() where T : class
{
IUnityContainer container = new UnityContainer().AddNewExtension<Interception>();
container.RegisterType<IBasicCodeService, BasicCodeService>(); container.Configure<Interception>().SetInterceptorFor<T>(new InterfaceInterceptor()); T t = container.Resolve<T>();
return t;
}
好了,搞定收工。看看调用的代码。so easy
class Program
{
static void Main(string[] args)
{
IBasicCodeService baService = BaseService.CreateService<IBasicCodeService>();
string userName = baService.SingleUserCode("user1");
List<string> listUserCode = baService.GetListUserCode("code1", "name1"); System.Console.WriteLine("生成日志个数:" + BaseService.LogMethods.Count); System.Console.ReadKey();
}
}
这里有一点要说明下,就是接口中有方法1(需记录Aop);方法2(不需记录)。这种情况下,若方法2引用方法1时,也想生成Aop的话,需这样调用,直接使用this是不行的
public string SingleUserCode(string userCode)
{
IBasicCodeService baService = BaseService.CreateService<IBasicCodeService>();
var listUserCode = baService.GetListUserCode(userCode, "name1"); return listUserCode[0];
} public List<string> GetListUserCode(string userCode, string userName)
{
return new List<string>() { "UserCode1", "UserCode2" };
}
介绍AOP比较全面的博客
1,关注微信公众号:小特工作室(也可直接扫描签名处二维码)
2,发送:示例4008
即可下载
基于微软企业库的AOP组件(含源码)的更多相关文章
- Prism6下的MEF:基于微软企业库的Cache
通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能.基于微软的企业库,我们的快速创建一个缓存的实现. 新建PrismSample.Infrastru ...
- 使用Microsoft EnterpriseLibrary(微软企业库)日志组件把系统日志写入数据库和xml文件
这里只是说明在项目中如何配置使用微软企业库的日志组件,对数据库方面的配置请参考其他资料. 1.在项目中添加Microsoft.Practices.EnterpriseLibrary.Data.dll. ...
- 在数据库访问项目中使用微软企业库Enterprise Library,实现多种数据库的支持
在我们开发很多项目中,数据访问都是必不可少的,有的需要访问Oracle.SQLServer.Mysql这些常规的数据库,也有可能访问SQLite.Access,或者一些我们可能不常用的PostgreS ...
- 升讯威ADO.NET增强组件(源码):送给喜欢原生ADO.NET的你
目前我们所接触到的许多项目开发,大多数都应用了 ORM 技术来实现与数据库的交互,ORM 虽然有诸多好处,但是在实际工作中,特别是在大型项目开发中,容易发现 ORM 存在一些缺点,在复杂场景下,反而容 ...
- [EntLib]微软企业库5.0 学习之路——第一步、基本入门
话说在大学的时候帮老师做项目的时候就已经接触过企业库了但是当初一直没明白为什么要用这个,只觉得好麻烦啊,竟然有那么多的乱七八糟的配置(原来我不知道有配置工具可以进行配置,请原谅我的小白). 直到去年在 ...
- 【公开课】《奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱》文字记录与反馈
本期分享的内容: <奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱> 时间:2016年11月02日 课程主讲人:叶锡文 从事商业智能行业,有丰富的实施经验,擅长 ...
- 微软企业库的Cache
微软企业库的Cache 通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能.基于微软的企业库,我们的快速创建一个缓存的实现. 新建PrismSamp ...
- 在开发框架中扩展微软企业库,支持使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库
在前面随笔<在代码生成工具Database2Sharp中使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库,实现免安装Oracle客户端,兼容3 ...
- 10月26日 奥威Power-BI基于微软示例库(MSOLAP)快速制作管理驾驶舱 腾讯课堂开课啦
本次课是基于olap数据源的案例实操课,以微软olap示例库Adventure Works为数据基础. AdventureWorks示例数据库为一家虚拟公司的数据,公司背景为大型跨国生产 ...
随机推荐
- SQL中MAX()
列column_name中的数据可以是数值.字符串或是日期时间数据类型.
- Android 双卡获取当前使用流量在线卡的信息
最近接触了一个项目,需要获取在线流量卡的信息,下面的方式,可以获取大部分手机的正确手机卡信息. 一 获取获取IMEI public static String getDeviced(int solt ...
- linux各种顔色代表
@linux中的各文件的颜色表示什么 白色:表示普通文件 蓝色:表示目录 绿色:表示可执行文件 红色:表示压缩文件 浅蓝色:链接文件 红色闪烁:表示链接的文件有问题 黄色:表示设备文件 灰色:表示其它 ...
- maven系列--maven常用命令
下一篇博客我会讲解用eclipse的m2插件来使用maven,这里先大概的了解下maven常用的命令.之后我在详细整理maven的生命周期,到时候会细致的讲解下这些指令应该要怎么使,maven都帮我们 ...
- C语言中函数可变参数解析
大多数时候,函数中形式参数的数目通常是确定的,在调用时要依次给出与形式参数对应的所有实际参数.但在某些情况下希望函数的参数个数可以根据需要确定.典型的例子有 大家熟悉的函数printf().scanf ...
- jdk源码->集合->ArrayList
类的属性 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomA ...
- 【转】Linux shell笔记
由于工作的需要,越来越多的接触到linux系统.最近看了<Linux与Unix Shell>这本书,安装书的章节整理了一些自己认为比较重要的命令,方便以后查阅. No.001 文件安全与权 ...
- c# 事件路由器
事件转发 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sys ...
- ASP.NET Core Web APi获取原始请求内容
前言 我们讲过ASP.NET Core Web APi路由绑定,本节我们来讲讲如何获取客户端请求过来的内容. ASP.NET Core Web APi捕获Request.Body内容 [HttpPos ...
- debug时ClassNotFound可能出现的原因
自我总结,欢迎拍砖! 目的:总结ClassNotFound可能出现的原因,方便以后定位该类问题. 原因:当项目中加了新类,debug或run时,报classnotfound,说明没有找到该类的clas ...