1
我正在使用AutoFac在MVC中實現Transaction-per-Request模式。我有以下幾點:Autofac,NHibernate ISession和MVC transaction-per-request。正確使用Session和Transaction的功能看起來像什麼?
public static void RegisterDaoFactory()
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterControllers(Assembly.GetAssembly(typeof(Streamus)));
containerBuilder.Register(x => NHibernateSessionManager.Instance.SessionFactory).SingleInstance();
containerBuilder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).InstancePerHttpRequest();
containerBuilder.Register(x => LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType)).As<ILog>().InstancePerHttpRequest();
IContainer container = containerBuilder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
public abstract class StreamusController : Controller
{
protected readonly ILog Logger;
protected new readonly ISession Session;
private ITransaction Transaction;
protected StreamusController(ILog logger, ISession session)
{
if (logger == null) throw new ArgumentNullException("logger");
if (session == null) throw new ArgumentNullException("session");
Logger = logger;
Session = session;
}
protected override void OnActionExecuting(ActionExecutingContext actionContext)
{
base.OnActionExecuting(actionContext);
Transaction = Session.BeginTransaction();
}
protected override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
try
{
if (Transaction.IsActive)
{
if (actionExecutedContext.Exception != null)
Transaction.Rollback();
else
Transaction.Commit();
}
}
finally
{
Transaction.Dispose();
}
}
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
}
Autofac打開和關閉ISession對我來說就像一個冠軍。我很確定我需要自己處理交易。
我錯過了什麼?