在 Web 应用程序中使用 Autofac 管理 NHibernate 事务的最佳方法是什么?
我的 session 方法是
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession())
.ContainerScoped();
对于ITransaction
,我有 found an example在 Google Code 上,但它在决定是否回滚时依赖于 HttpContext.Current.Error
。
有更好的解决办法吗? NHibernate 事务应该有什么范围?
最佳答案
我不久前发布了这个:
修改,让拦截器具备日志功能,并且[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;
}
}
关于asp.net-mvc - ASP.NET 中的 NHibernate 与 Autofac (MVC) : ITransaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1626243/