软件开发,离不开对日志的操作。日志可以帮助我们查找和检测问题,比较传统的日志是在方法执行前或后,手动调用日志代码保存。但自从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比较全面的博客

C#进阶系列——AOP?AOP!

 源码下载方式
1,关注微信公众号:小特工作室(也可直接扫描签名处二维码)
2,发送:示例4008
即可下载 

基于微软企业库的AOP组件(含源码)的更多相关文章

  1. Prism6下的MEF:基于微软企业库的Cache

    通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能.基于微软的企业库,我们的快速创建一个缓存的实现. 新建PrismSample.Infrastru ...

  2. 使用Microsoft EnterpriseLibrary(微软企业库)日志组件把系统日志写入数据库和xml文件

    这里只是说明在项目中如何配置使用微软企业库的日志组件,对数据库方面的配置请参考其他资料. 1.在项目中添加Microsoft.Practices.EnterpriseLibrary.Data.dll. ...

  3. 在数据库访问项目中使用微软企业库Enterprise Library,实现多种数据库的支持

    在我们开发很多项目中,数据访问都是必不可少的,有的需要访问Oracle.SQLServer.Mysql这些常规的数据库,也有可能访问SQLite.Access,或者一些我们可能不常用的PostgreS ...

  4. 升讯威ADO.NET增强组件(源码):送给喜欢原生ADO.NET的你

    目前我们所接触到的许多项目开发,大多数都应用了 ORM 技术来实现与数据库的交互,ORM 虽然有诸多好处,但是在实际工作中,特别是在大型项目开发中,容易发现 ORM 存在一些缺点,在复杂场景下,反而容 ...

  5. [EntLib]微软企业库5.0 学习之路——第一步、基本入门

    话说在大学的时候帮老师做项目的时候就已经接触过企业库了但是当初一直没明白为什么要用这个,只觉得好麻烦啊,竟然有那么多的乱七八糟的配置(原来我不知道有配置工具可以进行配置,请原谅我的小白). 直到去年在 ...

  6. 【公开课】《奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱》文字记录与反馈

        本期分享的内容: <奥威Power-BI基于微软示例库(MSSQL)快速制作管理驾驶舱> 时间:2016年11月02日 课程主讲人:叶锡文 从事商业智能行业,有丰富的实施经验,擅长 ...

  7. 微软企业库的Cache

    微软企业库的Cache 通常,应用程序可以将那些频繁访问的数据,以及那些需要大量处理时间来创建的数据存储在内存中,从而提高性能.基于微软的企业库,我们的快速创建一个缓存的实现. 新建PrismSamp ...

  8. 在开发框架中扩展微软企业库,支持使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库

    在前面随笔<在代码生成工具Database2Sharp中使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库,实现免安装Oracle客户端,兼容3 ...

  9. 10月26日 奥威Power-BI基于微软示例库(MSOLAP)快速制作管理驾驶舱 腾讯课堂开课啦

    本次课是基于olap数据源的案例实操课,以微软olap示例库Adventure Works为数据基础.        AdventureWorks示例数据库为一家虚拟公司的数据,公司背景为大型跨国生产 ...

随机推荐

  1. UITableViewCell滑动删除及移动

    实现Cell的滑动删除, 需要实现UITableView的代理UITableViewDelegate中如下方法: //先要设Cell可编辑 - (BOOL)tableView:(UITableView ...

  2. Hibernate 的原生 SQL 查询

    Hibernate除了支持HQL查询外,还支持原生SQL查询.         对原生SQL查询执行的控制是通过SQLQuery接口进行的,通过执行Session.createSQLQuery()获取 ...

  3. Java中实例方法、类方法和构造方法

    类方法,有static修饰符,典型的主函数public static void main(String[] args){}实例方法,就是一般的方法构造方法,没有返回值(就是连void都没有),方法名与 ...

  4. python_变量

    python中一切皆对象  什么是变量.变量名? --变量是存放数据的容器,变量名是区分容器的名字 例如 : a = 7,a就是变量的名字,叫a名字指向那个容器存放了数字 7 变量有什么形式?  变量 ...

  5. Maven以及在Maven在Myeclipse中的配置

    一.maven安装与配置1.到官网http://maven.apache.org/download.cgi下载maven压缩包,解压到指定文件夹.如:D:\apache-maven-3.3.92.添加 ...

  6. 04_Javascript初步第二天(下)

    错误对象 try{ aa();//这是一个未被定义的方法 }catch(e){ alert(e.name+":"+e.message);//输出:ReferenceError:aa ...

  7. HTML5与css3权威指南(一)

    doctype声明: <!DOCTYPE html> 字符编码: <meta charset="utf-8"> 不允许写结束标记:area,base,br. ...

  8. unix网络编程第2版(卷1)_第6章_同步_异步

    第6章 I/O复用:select和poll函数 6.1概述 在5.12节中,我们看到TCP客户同时处理两个输入:标准输入和TCP套接口.我们遇到的问题是客户阻塞于(标准输入上的)fgets调用,而服务 ...

  9. linux的定时任务服务crond(crontab)服务

    1,Crond: Crond是linux系统中用来定期执行命令或指定程序任务的一种服务或者软件.(Centos5以后默认存在) 当优化开机自启动的时候,第一个就是crond. Crond服务默认情况( ...

  10. HTML5之Notification简单使用

    var webNotification = { init: function() { if(!this.isSupport()) { console.log('不支持通知'); return; } t ...