最近公司新项目,须要搭架构进行开发,其中须要对一些日志进行输出,通过一番查找,发现不少博文都是经过Spring.Net、Unity、PostSharp、Castle Windsor这些方式实现AOP的。可是这不是我想要的,所以一番查找后,使用Autofac、DynamicProxy
该方式实现AOP。git
博主以为它的优点主要表如今:github
此处依赖自定义的日志组件,配置是否开启调试模式,若是启用调试模式,则会输出请求参数信息以及响应参数信息。
代码以下:c#
/// <summary> /// 日志 拦截器 /// </summary> public class LoggingInterceptor:IInterceptor { /// <summary> /// 日志记录器 /// </summary> private static readonly ILog Logger = Log.GetLog(typeof(LoggingInterceptor)); public void Intercept(IInvocation invocation) { try { if (Logger.IsDebugEnabled) { Logger.Caption("日志拦截器-调试信息"); Logger.Class(invocation.TargetType.FullName); Logger.Method(invocation.Method.Name); Logger.Params("参数:{0}", invocation.Arguments.ToJson()); } invocation.Proceed(); if (Logger.IsDebugEnabled) { if (invocation.ReturnValue != null && invocation.ReturnValue is IEnumerable) { dynamic collection = invocation.ReturnValue; Logger.Content("结果:行数:{0}", collection.Count); } else { Logger.Content("结果:{0}", invocation.ReturnValue.ToJson()); } Logger.Debug(); } } catch (Exception e) { Logger.Caption("日志拦截器-异常"); Logger.Class(invocation.TargetType.FullName); Logger.Method(invocation.Method.Name); Logger.Params("参数:{0}", invocation.Arguments.ToJson()); Logger.Exception(e); Logger.Error(); throw; } } }
博主对Autofac
进行了封装,可能与大家的配置不同,可是,Load(ContainerBuilder builder)
该方法内容是一致的,所以注入方式一致的。
经过定义IDependency
空接口方式,须要注入的类则继承该接口便可。
代码以下:架构
/// <summary> /// 应用程序IOC配置 /// </summary> public class IocConfig : ConfigBase { // 重写加载配置 protected override void Load(ContainerBuilder builder) { var assembly = this.GetType().GetTypeInfo().Assembly; builder.RegisterType<LoggingInterceptor>(); builder.RegisterAssemblyTypes(assembly) .Where(type => typeof(IDependency).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract) .AsImplementedInterfaces() .InstancePerLifetimeScope() .EnableInterfaceInterceptors() .InterceptedBy(typeof(LoggingInterceptor)); } }
输出日志以下:
ide
自定义日志组件可参考:JCE.DataCenter.Infrastructure
实现日志组件可参考:JCE.DataCenter.Logs模块化