c# - How do I handle transactions without code duplication? -


i seem repeat myself everytime want use transaction in post methods. can use action filter or something?

[httppost] public virtual actionresult create(createmodel model) {   if (!modelstate.isvalid)     return view(model);    var instruction = new instruction(currentuser);   mapper.map(model, instruction);    // how rid of this?   using (var uow = _unitofworkfactory.create())   {     _repository.save(instruction);      uow.savechanges();   }    return redirecttoaction("details", new {id = instruction.id}); } 

create new action filter checks modelstate , httpcontext.error property before creating , using unitofwork:

public class transactionalattribute : actionfilterattribute {   private iunitofwork _unitofwork;    public override void onactionexecuting(actionexecutingcontext filtercontext)   {     if (filtercontext.controller.viewdata.modelstate.isvalid && filtercontext.httpcontext.error == null)       _unitofwork = dependencyresolver.current.getservice<iunitofwork>();      base.onactionexecuting(filtercontext);   }    public override void onactionexecuted(actionexecutedcontext filtercontext)   {     if (filtercontext.controller.viewdata.modelstate.isvalid && filtercontext.httpcontext.error == null && _unitofwork != null)       _unitofwork.savechanges();      base.onactionexecuted(filtercontext);   } } 

a sample nhibernate implementation of unitofwork (register in ioc):

public class nhibernateunitofwork : iunitofwork {   private readonly isession _session;   private itransaction _transaction;    public nhibernateunitofwork(isession session)   {     _session = session;     _transaction = session.begintransaction();   }    public void dispose()   {     if (_transaction == null)       return;      if (!_transaction.wascommitted)       _transaction.rollback();      _transaction.dispose();     _transaction = null;   }    public void savechanges()   {     _transaction.commit();   }  } 

usage:

[httppost, transactional] public virtual actionresult create(createmodel model) {   if (!modelstate.isvalid)     return view(model);    var instruction = new instruction(currentuser);   mapper.map(model, instruction);   _repository.save(instruction);    return redirecttoaction("details", new {id = instruction.id}); } 

source: http://blog.gauffin.org/2012/06/how-to-handle-transactions-in-asp-net-mvc3/


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -