NHibernate与ASP.NET中的Autofac(MVC):ITransaction

And*_*kin 6 nhibernate asp.net-mvc transactions autofac

在Web应用程序中使用Autofac管理NHibernate事务的最佳方法是什么?

我的会话方法是

builder.Register(c => c.Resolve<ISessionFactory>().OpenSession())
       .ContainerScoped();
Run Code Online (Sandbox Code Playgroud)

因为ITransaction,我在Google Code上找到了一个示例,但它HttpContext.Current.Error在决定是否回滚时依赖于它.

有更好的解决方案吗?NHibernate事务应该具有什么范围?

dmo*_*ord 4

我不久前发布了这个:

http://groups.google.com/group/autofac/browse_thread/thread/f10badba5fe0d546/e64f2e757df94e61?lnk=gst&q=transaction#e64f2e757df94e61

修改后,让拦截器具备日志功能,并且[Transaction]属性也可以用在类上。

[global::System.AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class TransactionAttribute : Attribute
{
}


public class ServicesInterceptor : Castle.Core.Interceptor.IInterceptor
{
    private readonly ISession db;
    private ITransaction transaction = null;

    public ServicesInterceptor(ISession db)
    {
        this.db = db;
    }

    public void Intercept(IInvocation invocation)
    {
        ILog log = LogManager.GetLogger(string.Format("{0}.{1}", invocation.Method.DeclaringType.FullName, invocation.Method.Name));

        bool isTransactional = IsTransactional(invocation.Method);
        bool iAmTheFirst = false;

        if (transaction == null && isTransactional)
        {
            transaction = db.BeginTransaction();
            iAmTheFirst = true;
        }

        try
        {
            invocation.Proceed();

            if (iAmTheFirst)
            {
                iAmTheFirst = false;

                transaction.Commit();
                transaction = null;
            }
        }
        catch (Exception ex)
        {
            if (iAmTheFirst)
            {
                iAmTheFirst = false;

                transaction.Rollback();
                db.Clear();
                transaction = null;
            }

            log.Error(ex);
            throw ex;
        }
    }

    private bool IsTransactional(MethodInfo mi)
    {
        var atrClass = mi.DeclaringType.GetCustomAttributes(false);

        foreach (var a in atrClass)
            if (a is TransactionAttribute)
                return true;

        var atrMethod = mi.GetCustomAttributes(false);

        foreach (var a in atrMethod)
            if (a is TransactionAttribute)
                return true;

        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)