How to rollback nHibernate transaction when an exception occurs during request having Ninject for managing sessions? -
How to rollback nHibernate transaction when an exception occurs during request having Ninject for managing sessions? -
i utilize nhibernate orm , ninject ioc. create nhibernate sessions per custom scope (which can assume per request). begin transaction onactivation. commit transaction ondeactivation.
the problem if exception happens during request want rollback transaction rather committing it. thought how observe (in clean way, using ninject context) exception has happened?
note: not concerned exceptions can happen on commit can grab in next code , role easily.
protected void bindwithsessionwrapper<t>(func<icontext, t> creationfunc) t : isessionwrapper { bind<t>().tomethod(creationfunc) .inscope(x => new ninjectcustomscope()) // work in progress !!! .onactivation(t => t.session.begintransaction(isolationlevel.readcommitted)) .ondeactivation((c, t) => { t.session.transaction.commit(); t.session.dispose(); }); }
update:
i followed suggestion @batterybackupunit. added next error eventhandler:
error += (s, e) => { httpcontext.current.items["errorraised"] = true; };
and modified ondeactivation this:
ondeactivation(t => { if ((bool?)httpcontext.current.items["errorraised"] == true) t.session.transaction.rollback(); else t.session.transaction.commit(); t.session.dispose(); });
it works fine, improve if ninject take care of setting flag in context if exception happened :)
how implementing ihttpmodule
, subscribing error
event? described here
in error
event handler, utilize system.web.mvc.dependencyresolver.current.getservice(typeof (isession))
retrieve current session , rollback transaction.
note, however, in case request did not utilize session, create one, quite superfluous.
you might checking whether transaction started , rolling back. you'd still create session unnecessarily.
you farther improve using error
event handler set flag on httpcontext.current.items
, like
httpcontext.current.items["rollbacktransaction"] = true;
and utilize in ondeactivation
of session like:
.ondeactivation((c, t) => { if(httpcontext.current.items.contains("rollbacktransaction"]) { t.session.transaction.rollback(); } else { t.session.transaction.commit(); } t.session.dispose(); });
please note httpcontext
thread local, means when switch threads may null
or -worst case - might httpcontext
.
please note unable seek out may not work. feedback appreciated.
nhibernate transactions ninject rollback
Comments
Post a Comment