2014-03-02 27 views
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對我來說就像一個冠軍。我很確定我需要自己處理交易。

我錯過了什麼?

回答

0

我會在控制器操作中直接調用BeginTransaction(),以及何時需要它。您通常希望交易的壽命可能縮短。另外,通過這種方式,您可以選擇不在不需要的情況下打開事務,如重定向。

此外,不要忘記使用​​,以便您的交易始終處置,例外與否。

相關問題