库主场迎战的UnitOfWork主场、UnitOfWork

2023-09-04 23:38:24 作者:凉栀

我目前的观点是,库中应包含的实体,具体的修改方法,如添加,删除等,并应的UnitOfWork只包含方法是相关的是,一般像提交(也称为调用SaveChanges,的SubmitChanges)和rollback (也称为ClearChanges)。不过,马丁·福勒在他的文章有关的UnitOfWork 建议将所有的修改方法添加到的UnitOfWork。

My current point of view is that repository should contain entity-specific modification methods like Add, Delete, etc. and UnitOfWork should contain just methods that are relevant to it in general like Commit (also known as SaveChanges, SubmitChanges) and Rollback (also known as ClearChanges). But Martin Fowler in his article about UnitOfWork suggests to add all modification methods to UnitOfWork.

那么哪一种方式比较好,现在,在EF和NHibernate的世界吗?

So which way is better now, in the world of EF and NHibernate?

更新。 我要指出,即使有我的preferable方法最终通过资源库的所有修改进入的UnitOfWork已内置入EF上下文或NHibernate的会话。而我的UnitOfWork更像UnitOfWorkManager(其中管理内部ORM的UnitOfWork)。

Update. I should note that even with my preferable approach finally all modifications through repository go into UnitOfWork which is built into EF Context or NHibernate Session. And my UnitOfWork is more like UnitOfWorkManager (which manages internal ORM UnitOfWork).

推荐答案

在的UnitOfWork的NHibernate的全球主要功能由ISession的实现。 ISession的跟踪发生了什么变化,你并不需要有像RegisterClean或RegisterDirty方法。对于较大的项目是非常有用的隐藏的ISession使用自己的类,它可以被称为的UnitOfWork。例如:

In NHibernate world main functionality of UnitOfWork in implemented by ISession. ISession keeps track of what has changed and you do not need to have methods like RegisterClean or RegisterDirty. For a larger projects it is useful to hide ISession by using your own class that can be called UnitOfWork. For example:

public class UnitOfWork {

    private readonly ISession _session;

    public void BeginTransaction();

    public void Commit();

    public void Rollback();

    public IRepositoryFactory AllRepositories;
}

从应用程序code隐藏的ISession的优点是,这个code不会引用NHibernate的直接这就加强更好的层次感。换句话说,它会为应用层更难开始使用NHibernate的API直接绕过数据访问层。

The advantage of hiding ISession from application code is that this code will not reference NHibernate directly which enforces better layering. In other words it will be harder for application layer to start using NHibernate API directly, bypassing data access layer.

该库本身包含添加新对象,并可能删除方法:

The repository itself will contain methods for adding new objects and possibly deleting:

public interface IOrdersRepository {

    public IList<Order> FindPending();

    public void AddNew(Order order);

    public void Delete(Order order);
}