Unit of work template in asp.net mvc application

I looked at this class blog called "NHibernate and the work block" and asked a question about the best place to use UnitOfWork.Start in the asp.net mvc project.

My SLN is divided into the following projects: -

MVC project Repository NHibernateUnitOfWork 

I have an interface: -

  public interface INameRepository ... IList<Name> GetByOrigin(int OriginId) ... 

I have a specific implementation

  public class NameRepository : INameRepository ... public IList<Name> GetByOrigin(int OriginId) { using (UnitOfWork.Start()) { var query = session.Linq<... return query; } } ... 

My question is whether I wrap all my methods in all my repositories using (UnitOfWork.Start ()) or is there a better approach?

I am using nHibernate, asp.net mvc.

+6
c # asp.net-mvc unit-of-work nhibernate
source share
2 answers

With a single job template, you do not put each data processing method in a separate unit of work. You use a unit of work around all the work that needs to be done, which in most cases in a web application is a web request. The idea is that the request may fail or succeed. When you add 2 items to the database in one query, they should be added or not. Not just one of them. In most cases, the easiest way to start a unit of work in an mvc application (or other web application) is with the start and end methods of the global.asax request

 class Global { BeginRequest() { servicelocater.get<unitofwork>().start(); } EndRequest() { var unit = servicelocater.Get<Unitofwork>(); try { unit.commit(); } catch { unit.rollback(); throw; } } } class Repository<T> { public Repository(INHibernateUnitofwork unitofwork) { this.unitofwork = unitofwork; } public void Add(T entity) { unitofwork.session.save(entity); } } 
+4
source share

I think Sharp Architecture solves this pretty well. What they do is put the block of work in the ASP.Net MVC Action Filter. Basically you can define a transactional action filter, for example

 public class TransactionAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { UnitOfWork.Start(); } public override void OnActionExecuted(ActionExecutedContext filterContext) { UnitOfWork.Stop(); } }
public class TransactionAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { UnitOfWork.Start(); } public override void OnActionExecuted(ActionExecutedContext filterContext) { UnitOfWork.Stop(); } } 

and in your controller class put the Transaction attribute in the Action Result method

+2
source share

All Articles