最近公司新項目,須要搭架構進行開發,其中須要對一些日誌進行輸出,通過一番查找,發現不少博文都是經過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模塊化