The unit of work pattern within a asp.net mvc application

前端 未结 2 947
后悔当初
后悔当初 2021-02-02 04:08

I have been looking at this excellant blog titled \"NHibernate and the Unit of Work Pattern\" and have a question regarding the best place to use UnitOfWork.Start in a asp.net m

2条回答
  •  清酒与你
    2021-02-02 04:44

    With the unit of work pattern, you don't put every dataaccess method in a separate unit of work. You use the unit of work around the whole work that needs to be done, which is in most cases in a web application a webrequest. The idea is that a request can fail, or succeed. When you add 2 items to the database during one request, the should be both added, or not. Not just one of them. In most cases, the easiest way to start a unit of work in a mvc (or other web) application is in the begin and end request methods of the global.asax

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

提交回复
热议问题