[AOP系列]Autofac+Castle實現AOP事務

1、前言

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

2、使用AOP的優點

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

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

3、引用庫

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

4、實現思路

4.1 定義屬性

定義屬性,經過當前方法是否包含該屬性進行判斷開啓事務,若是存在該屬性則開啓事務,不然忽略事務。
事務屬性能夠設置超時時間、事務範圍以及事務隔離級別。
代碼以下:ide

/// <summary>
/// 開啓事務屬性
/// </summary>
[AttributeUsage(AttributeTargets.Method,Inherited = true)]
public class TransactionCallHandlerAttribute:Attribute
{
    /// <summary>
    /// 超時時間
    /// </summary>
    public int Timeout { get; set; }

    /// <summary>
    /// 事務範圍
    /// </summary>
    public TransactionScopeOption ScopeOption { get; set; }

    /// <summary>
    /// 事務隔離級別
    /// </summary>
    public IsolationLevel IsolationLevel { get; set; }

    public TransactionCallHandlerAttribute()
    {
        Timeout = 60;
        ScopeOption=TransactionScopeOption.Required;
        IsolationLevel=IsolationLevel.ReadCommitted;
    }
}

4.2 切面實現

獲取當前方法是否包含TransactionCallHandlerAttribute該屬性,若是有該屬性則開啓事務。
本人在此處加入開發模式判斷,用於沒設置MSDTC產生異常的問題,若是不須要可忽略。
另外日誌功能自行實現便可。
代碼以下:模塊化

/// <summary>
/// 事務 攔截器
/// </summary>
public class TransactionInterceptor:IInterceptor
{
    //可自行實現日誌器,此處可忽略
    /// <summary>
    /// 日誌記錄器
    /// </summary>
    private static readonly ILog Logger = Log.GetLog(typeof(TransactionInterceptor));

    // 是否開發模式
    private bool isDev = false;
    public void Intercept(IInvocation invocation)
    {
        if (!isDev)
        {
            MethodInfo methodInfo = invocation.MethodInvocationTarget;
            if (methodInfo == null)
            {
                methodInfo = invocation.Method;
            }
                            
            TransactionCallHandlerAttribute transaction =
                methodInfo.GetCustomAttributes<TransactionCallHandlerAttribute>(true).FirstOrDefault();
            if (transaction != null)
            {
                TransactionOptions transactionOptions = new TransactionOptions();
                //設置事務隔離級別
                transactionOptions.IsolationLevel = transaction.IsolationLevel;
                //設置事務超時時間爲60秒
                transactionOptions.Timeout = new TimeSpan(0, 0, transaction.Timeout);
                using (TransactionScope scope = new TransactionScope(transaction.ScopeOption, transactionOptions))
                {
                    try
                    {
                        //實現事務性工做
                        invocation.Proceed();
                        scope.Complete();
                    }
                    catch (Exception ex)
                    {
                        // 記錄異常
                        throw ex;
                    }
                }
            }
            else
            {
                // 沒有事務時直接執行方法
                invocation.Proceed();
            }
        }
        else
        {
            // 開發模式直接跳過攔截
            invocation.Proceed();
        }
    }
}

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<TransactionInterceptor>();
        builder.RegisterAssemblyTypes(assembly)
            .Where(type => typeof(IDependency).IsAssignableFrom(type) && !type.GetTypeInfo().IsAbstract)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope()
            .EnableInterfaceInterceptors()
            .InterceptedBy(typeof(TransactionInterceptor));
    }
}

5、例子

/// <summary>
/// 添加文章
/// </summary>
/// <param name="name"></param>
[TransactionCallHandler]
public void AddArticle(string name)
{
    BasArticle model=new BasArticle();
    model.ArticleID = Guid.Empty;//故意重複,判斷是否會回滾。
    model.Code = TimestampId.GetInstance().GetId();
    model.Name = name;
    model.Status = 1;
    model.Creater = "測試";
    model.Editor = "測試";
    this._basArticleRepository.Insert(model);            
}
相關文章
相關標籤/搜索