Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>An alternative way to handle transactions is to use an <code>IActionFilter</code> Open the transaction in <code>OnActionExecuting</code> and commit on <code>OnActionExecuted</code></p> <pre><code>public class TransactionFilter : IActionFilter { private readonly ISession session; private ITransaction transaction; public TransactionFilter(ISession session) { this.session = session; } public void OnActionExecuting(ActionExecutingContext filterContext) { this.transaction = this.session.BeginTransaction(); } public void OnActionExecuted(ActionExecutedContext filterContext) { try { if (this.transaction.IsActive) { if (filterContext.Exception == null) { this.transaction.Commit(); } else { this.transaction.Rollback(); } } } finally { this.transaction.Dispose(); } } } </code></pre> <p>Define an attribute to mark the actions that use a transaction:</p> <pre><code>[AttributeUsage(AttributeTargets.Method)] public class TransactionAttribute : Attribute { } </code></pre> <p>Change your Ninject configuration:</p> <pre><code>internal class ServiceModule : NinjectModule { public override void Load() { var helper = new NHibernateHelper(connectionString); Bind&lt;ISessionFactory&gt;().ToConstant(helper.SessionFactory) .InSingletonScope(); Bind&lt;ISession&gt;().ToProvider&lt;SessionProvider&gt;().InRequestScope(); Bind(typeof(IRepository&lt;&gt;)).To(typeof(Repository&lt;&gt;)); Bind(typeof(IIntKeyedRepository&lt;&gt;)).To(typeof(Repository&lt;&gt;)); BindFilter&lt;TransactionFilter&gt;(FilterScope.Action, null) .WhenActionMethodHas&lt;TransactionAttribute&gt;(); } } </code></pre> <p>Finally change your controller:</p> <pre><code>public FAQController(IIntKeyedRepository&lt;FAQ&gt; faqRepository) { _faqRepository = faqRepository; } [Transaction] [Authorize] [AcceptVerbs(HttpVerbs.Post)] [ValidateInput(false)] public ActionResult AddFAQ(FAQ contact) { var c = new FAQ {Question = contact.Question, Answer = contact.Answer}; _faqRepository.Add(c); return RedirectToAction("Index"); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload