[AOP系列]Autofac+Castle實現AOP日誌

1、前言

最近公司新項目,須要搭架構進行開發,其中須要對一些日誌進行輸出,通過一番查找,發現不少博文都是經過Spring.Net、Unity、PostSharp、Castle Windsor這些方式實現AOP的。可是這不是我想要的,所以一番查找後,使用Autofac、DynamicProxy該方式實現AOP。git

2、使用AOP的優點

博主以爲它的優點主要表如今:github

  • 將通用功能從業務邏輯中抽離出來,就能夠省略大量重複代碼,有利於代碼的操做和維護。
  • 在軟件設計時,抽出通用功能(切面),有利於軟件設計的模塊化,下降軟件架構的複雜程度。也就是說通用的功能就是一個單獨的模塊,在項目的主業務裏面是看不到這些通用功能的設計代碼的。

3、引用庫

  • Autofac:4.6
  • Autofac.Extras.DynamicProxy:4.1.0
  • Castle.Core:3.2.2
  • log4net:2.08

4、實現思路

4.1 切面實現

此處依賴自定義的日誌組件,配置是否開啓調試模式,若是啓用調試模式,則會輸出請求參數信息以及響應參數信息。
代碼以下: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;
        }
    }
}

4.3 切面注入

博主對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));
    }
}

5、例子

輸出日誌以下:

ide

6、相關源碼

自定義日誌組件可參考:JCE.DataCenter.Infrastructure
實現日誌組件可參考:JCE.DataCenter.Logs模塊化

相關文章
相關標籤/搜索