工作模式的一个asp.net MVC应用程序中的单元 [英] The unit of work pattern within a asp.net mvc application

查看:149
本文介绍了工作模式的一个asp.net MVC应用程序中的单元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找这个excellant <一个href=\"http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/10/nhibernate-and-the-unit-of-work-pattern.aspx\"相对=nofollow>博客名为NHibernate和工作模式的单位,并有关于在asp.net mvc的项目中使用UnitOfWork.Start的最佳场所的问题。

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 mvc project.

我的SLN分为以下项目: -

My SLN is broken down into the following projects:-

 MVC project
 Repository
 NHibernateUnitOfWork

我有一个接口: -

I have an interface:-

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

我有一个具体的实施

I have a concrete implementation

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

我的问题是我总结我的所有的存储库中的所有方法,使用(UnitOfWork.Start()),或是否有更好的方法?

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

我使用NHibernate,asp.net mvc的。

I am using nHibernate, asp.net mvc.

推荐答案

使用工作模式的单位,你不把所有的数据访问方法,工作独立的单元。您可以使用工作单位周围需要做的,这是在大多数情况下,在Web应用程序中的WebRequest整部作品。这个想法是,一​​个请求可能失败,或成功。当一个请求过程中添加2项数据库中,既要增加,还是不行。不只是其中之一。在大多数情况下,最简单的方法在MVC开始工作单位(或其他网络)的应用是在Global.asax

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<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);
     }
}

这篇关于工作模式的一个asp.net MVC应用程序中的单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆