I am using nHibernate for ORM and Ninject for IoC. I create nHibernate sessions for each custom scope (which you can take as a request). I am starting an onActivation transaction. I am committing an onDeactivation transaction.
The problem is that if an exception occurs during the request, I want to cancel the transaction, not commit it. Any idea how to detect (in pure form, most likely using the Ninject Context) that an exception has occurred?
Note. I am not interested in exceptions that may occur during commit, which I can easily catch in the following code and role.
protected void BindWithSessionWrapper<T>(Func<IContext, T> creationFunc) where T : ISessionWrapper
{
Bind<T>().ToMethod(creationFunc)
.InScope(x => new NinjectCustomScope())
.OnActivation(t => t.Session.BeginTransaction(IsolationLevel.ReadCommitted))
.OnDeactivation((c, t) =>
{
t.Session.Transaction.Commit();
t.Session.Dispose();
});
}
Update:
I followed the @BatteryBackupUnit suggestion. Therefore, I added the following to the Error EventHandler:
Error += (s, e) =>
{
HttpContext.Current.Items["ErrorRaised"] = true;
};
OnDeactivation, :
OnDeactivation(t =>
{
if ((bool?)HttpContext.Current.Items["ErrorRaised"] == true)
t.Session.Transaction.Rollback();
else
t.Session.Transaction.Commit();
t.Session.Dispose();
});
, , Ninject , , :)