gpt4 book ai didi

asp.net-mvc - ASP.NET 中的 NHibernate 与 Autofac (MVC) : ITransaction

转载 作者:行者123 更新时间:2023-12-03 02:49:21 24 4
gpt4 key购买 nike

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

我的 session 方法是

builder.Register(c => c.Resolve<ISessionFactory>().OpenSession())
.ContainerScoped();

对于ITransaction,我有 found an example在 Google Code 上,但它在决定是否回滚时依赖于 HttpContext.Current.Error

有更好的解决办法吗? NHibernate 事务应该有什么范围?

最佳答案

我不久前发布了这个:

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;
}
}

关于asp.net-mvc - ASP.NET 中的 NHibernate 与 Autofac (MVC) : ITransaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1626243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com